-->

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

2019-03-25 20:44发布

问题:

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!