Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 352
drenda Avatar asked Feb 20 '15 18:02

drenda


People also ask

Can I use @value in @service?

@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.

What does @value mean in spring boot?

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.

How does @value work in spring?

@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.

Can we inject null and empty string values in spring beans?

In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null> element.


2 Answers

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.

like image 120
Evgeni Dimitrov Avatar answered Sep 19 '22 22:09

Evgeni Dimitrov


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.

like image 41
mahesh chakravarthi Avatar answered Sep 17 '22 22:09

mahesh chakravarthi