Spring @Value(“${}”) often null

假如想象 提交于 2019-11-30 14:48:50

问题


I'm using Spring Boot application. In some @Component class @Value fields are loaded, instead on other classes they are always null.

Seems that @Value(s) are loaded after my @Bean/@Component are created.

I need to load some values from a properties file in my @Bean.

Have you some suggestion?


回答1:


The properties(and all of the bean dependencies) are injected after the bean is constructed(the execution of the constructor).

You can use constructor injection if you need them there.

@Component
public class SomeBean {
    private String prop;
    @Autowired
    public SomeBean(@Value("${some.prop}") String prop) {
        this.prop = prop;
        //use it here
    }
}

Another option is to move the constructor logic in method annotated with @PostConstruct it will be executed after the bean is created and all it's dependencies and property values are resolved.




回答2:


Have you tried:

@Component
@PropertySource("file:/your/file/path")
public class MyBean {

  private @Value("${property}") String property;
  ...
}



回答3:


It can happen when you are resolving it into a static variable. I had observed this sometime back and resolved it just by removing static. As people always say, exercise caution while using static.




回答4:


Another possible reason is that the '@Value' lines are below the lines that need these properties/values.

I spent a lot of time debugging this problem, and found out that the order of lines matters!



来源:https://stackoverflow.com/questions/28636060/spring-value-often-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!