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

2019-03-25 20:29发布

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?

4条回答
倾城 Initia
2楼-- · 2019-03-25 20:41

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.

查看更多
家丑人穷心不美
3楼-- · 2019-03-25 20:44

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.

查看更多
狗以群分
4楼-- · 2019-03-25 20:54

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!

查看更多
beautiful°
5楼-- · 2019-03-25 20:55

Have you tried:

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

  private @Value("${property}") String property;
  ...
}
查看更多
登录 后发表回答