springboot註解@Value老是報Could not resolve placeholder的問題

場景:spring

兩個配置文件:db.properties,application.properties數據庫

在數據庫配置裏面引用db.propertiesapp

<bean id="propertyPlaceholderConfigurer" class="...">
        <property name="locations">
            <list>
                <value>classpath*:/db.properties</value>
                <value>file:/etc/db.properties</value>
            </list>
        </property>
    </bean>

這時候,application.properties裏面的屬性就不會被加載進去了,若是你使用@Value,就會報Could not resolve placeholderthis

@Controller
public class FirstController {
    
    @Value("${welcome.message}")
    private String test;

    @RequestMapping("/getw")
    public String welcome(Map<String, Object> model) {
        //model.put("message", this.message);
        System.out.println(test);
        return "my";
    }

}

這樣使用就會報Could not resolve placeholderspa

 

解決:code

把db.properties的內容放到application.properties,而後這邊引用:blog

<bean id="propertyPlaceholderConfigurer" class="...">
        <property name="locations">
            <list>
                <value>classpath*:/application.properties</value>
                <value>file:/etc/application.properties</value>
            </list>
        </property>
    </bean>

或者兩個文件都加載get

<bean id="propertyPlaceholderConfigurer" class="...">
        <property name="locations">
            <list>
                <value>classpath*:/application.properties</value>
                <value>classpath*:/db.properties</value>
                <value>file:/etc/application.properties</value>
            </list>
        </property>
    </bean>

緣由是spring的加載機制:Spring容器採用反射掃描的發現機制,在探測到Spring容器中有一個org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就會中止對剩餘PropertyPlaceholderConfigurer的掃描(Spring 3.1已經使用PropertySourcesPlaceholderConfigurer替代PropertyPlaceholderConfigurer了),因此根據加載的順序,配置的第二個property-placeholder就被沒有被spring加載,因此在使用@Value注入的時候佔位符就解析不了io

相關文章
相關標籤/搜索