Spring @Value ("$ {}") is often null

I am using the Spring boot application. In some @Component classes, @Value are loaded, while in other classes they are always null .

It seems that @Value (s) are loading after creating @Bean / @Component .

I need to load some values ​​from the properties file in @Bean .

Do you have any suggestions?

+5
source share
3 answers

Properties (and all bean dependencies) are introduced after the bean is created (constructor execution).

You can use constructor injection if you need them.

 @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 the method annotated with @PostConstruct , which will be performed after the bean is created, and all its dependencies and property values ​​will be resolved.

+15
source

You tried:

 @Component @PropertySource("file:/your/file/path") public class MyBean { private @Value("${property}") String property; ... } 
0
source

Another possible reason is that @Value strings are below strings that need these properties / values.

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

-1
source

Source: https://habr.com/ru/post/1213825/


All Articles