zoukankan      html  css  js  c++  java
  • 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注入的时候占位符就解析不了

  • 相关阅读:
    Eclipse (indigo) 中安装jdk包并执行Maven
    UVA
    Android 仿QQ界面的实现
    Ajax是什么
    jieba.NET与Lucene.Net的集成
    jieba中文分词的.NET版本:jieba.NET
    SharePoint 2013技巧分享系列
    SharePoint 2013常用开发工具分享
    SharePoint 2013技巧分享系列
    SharePoint 2013技巧分享系列
  • 原文地址:https://www.cnblogs.com/tiramisuyj/p/9521211.html
Copyright © 2011-2022 走看看