西木-Lee

 

springboot @Value获取值为空,解决办法

在spring中,常常使用 @Value("${property}") 从application.properties中取值,需要注意两点

  1. 使用 @Value 的类不能使用 new 关键字进行实例化对象,必须采用 依赖注入的方式进行实例化
  2. 不能使用显式的构造方法

否则,将取不到值.解决方法如下:

  •   删除显式的构造方法,需要使用构造方法初始化的内容可以使用@PostConstruct
@PostConstruct //加上该注解表明该方法会在bean初始化后调用
private void init() {
  //添加你的内容
}

 

  •   使用构造方法注入
public LogConsumer(@Value("${report.period}") long reportPeriod) {
        this.reportPeriod = reportPeriod;
        System.out.println(reportPeriod + "1111111111111111111111111111111111111111");
        
    }

 

posted on 2018-08-08 17:44  西木-Lee  阅读(2925)  评论(1编辑  收藏  举报

导航