springboot注解@Value总是报Could not resolve placeholder的问题

今天药忘吃喽~ 2023-03-01 05:35 41阅读 0赞

场景:

两个配置文件:db.properties,application.properties,在数据库配置里面引用db.properties

  1. <bean id="propertyPlaceholderConfigurer" class="...">
  2. <property name="locations">
  3. <list>
  4. <value>classpath*:/db.properties</value>
  5. <value>file:/etc/db.properties</value>
  6. </list>
  7. </property>
  8. </bean>

这时候,application.properties里面的属性就不会被加载进去了,如果你使用@Value,就会报Could not resolve placeholder。

  1. @Controller
  2. public class FirstController {
  3. @Value("${welcome.message}")
  4. private String test;
  5. @RequestMapping("/getw")
  6. public String welcome(Map<String, Object> model) {
  7. //model.put("message", this.message);
  8. System.out.println(test);
  9. return "my";
  10. }
  11. }

这样使用就会报Could not resolve placeholder。

解决:把db.properties的内容放到application.properties,然后这边引用:

  1. <bean id="propertyPlaceholderConfigurer" class="...">
  2. <property name="locations">
  3. <list>
  4. <value>classpath*:/application.properties</value>
  5. <value>file:/etc/application.properties</value>
  6. </list>
  7. </property>
  8. </bean>

或者两个文件都加载:

  1. <bean id="propertyPlaceholderConfigurer" class="...">
  2. <property name="locations">
  3. <list>
  4. <value>classpath*:/application.properties</value>
  5. <value>classpath*:/db.properties</value>
  6. <value>file:/etc/application.properties</value>
  7. </list>
  8. </property>
  9. </bean>

原因是spring的加载机制:Spring容器采用反射扫描的发现机制,在探测到Spring容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描(Spring 3.1已经使用PropertySourcesPlaceholderConfigurer替代PropertyPlaceholderConfigurer了),所以根据加载的顺序,配置的第二个property-placeholder就被没有被spring加载,所以在使用@Value注入的时候占位符就解析不了。

转自:https://www.cnblogs.com/tiramisuyj/p/9521211.html

发表评论

表情:
评论列表 (有 0 条评论,41人围观)

还没有评论,来说两句吧...

相关阅读