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?
@Value annotation can be used within classes annotated with @Configuration , @Component and other stereotype annotations like @Controller , @Service etc. The actual processing of @Value annotation is performed by BeanPostProcessor and so @Value cannot be used within BeanPostProcessor class types.
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.
@Value is a Java annotation that is used at the field or method/constructor parameter level and it indicates a default value for the affected argument. It is commonly used for injecting values into configuration variables - which we will show and explain in the next part of the article.
In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null> element.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With