1. 程式人生 > >springboot註解@Value總是報Could not resolve placeholder的問題

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

boot system this ati quest code test 順序 sage

場景:

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

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

<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 placeholder

@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 placeholder

解決:

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

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

或者兩個文件都加載

<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註入的時候占位符就解析不了

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