I have a very simple Spring Boot app that I\'m trying to get working with some externalised configuration. I\'ve tried to follow the information on the spring boot documenta
The way you are performing the injection of the property will not work, because the injection is done after the constructor is called.
You need to do one of the following:
Better solution
@Component
public class MyBean {
private final String prop;
@Autowired
public MyBean(@Value("${some.prop}") String prop) {
this.prop = prop;
System.out.println("================== " + prop + "================== ");
}
}
Solution that will work but is less testable and slightly less readable
@Component
public class MyBean {
@Value("${some.prop}")
private String prop;
public MyBean() {
}
@PostConstruct
public void init() {
System.out.println("================== " + prop + "================== ");
}
}
Also note that is not Spring Boot specific but applies to any Spring application
follow these steps. 1:- create your configuration class like below you can see
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
@Configuration
public class YourConfiguration{
// passing the key which you set in application.properties
@Value("${some.pro}")
private String somePro;
// getting the value from that key which you set in application.properties
@Bean
public String getsomePro() {
return somePro;
}
}
2:- when you have a configuration class then inject in the variable from a configuration where you need.
@Component
public class YourService {
@Autowired
private String getsomePro;
// now you have a value in getsomePro variable automatically.
}