SpringBoot @Value获取application.properties中的配置无效的问题
无效的原因主要是要注意@Value使用的注意事项:1、不能作用于静态变量(static);2、不能作用于常量(final);3、不能在非注册的类中使用(需使用@Componet、@Configuration等);4、使用有这个属性的类时,只能通过@Autowired的方式,用new的方式是不会自动注入这些配置的。这些注意事项也是由它的原理决定的:springboot启动过程中,有两个比较重要的过程
·
无效的原因主要是要注意@Value使用的注意事项:
- 1、不能作用于静态变量(static);
- 2、不能作用于常量(final);
- 3、不能在非注册的类中使用(需使用@Componet、@Configuration等);
- 4、使用有这个属性的类时,只能通过@Autowired的方式,用new的方式是不会自动注入这些配置的。
- 5、@Value引用的类一定在使用的时候是通过@Autowired的,自己new的对象肯定不会注入
这些注意事项也是由它的原理决定的:
springboot启动过程中,有两个比较重要的过程,如下:
- 1 、扫描,解析容器中的bean注册到beanFactory上去,就像是信息登记一样。
- 2、 实例化、初始化这些扫描到的bean。
@Value
的解析就是在第二个阶段。BeanPostProcessor
定义了bean初始化前后用户可以对bean进行操作的接口方法,它的一个重要实现类AutowiredAnnotationBeanPostProcessor
正如javadoc所说的那样,为bean中的@Autowired
和@Value
注解的注入功能提供支持。
下面说下两种方式:
resource.test.imageServer=http://image.everest.com
1、
@Configuration
public class EverestConfig {
@Value("${resource.test.imageServer}")
private String imageServer;
public String getImageServer() {
return imageServer;
}
}
2、
@Component
@ConfigurationProperties(prefix = "resource.test")
public class TestUtil {
public String imageServer;
public String getImageServer() {
return imageServer;
}
public void setImageServer(String imageServer) {
this.imageServer = imageServer;
}
}
然后在需要的地方注入就可
@Autowired
private TestUtil testUtil;
@Autowired
private EverestConfig everestConfig;
@GetMapping("getImageServer")
public String getImageServer() {
return testUtil.getImageServer();
// return everestConfig.getImageServer();
}
更多推荐
所有评论(0)