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

java, spring, spring-bean, spring-boot, spring-properties

Solution

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.

Problem

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?

Original source