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


場景:

兩個配置文件: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注入的時候占位符就解析不了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM