Reputation: 56
In out project we don't use setter or filed injection, we use only constructor injection, and I know that both options 1. and 2. may work.
Or spring boot 2+ makes something, and I should better use option 1. instead of 2. I can't imagine case when option 1 will go wrong
@Component
@ConfigurationProperties("config")
public class ServiceConfigProperties {
// .... some code
}
@Component
public class Service {
private boolean skipCheck;
public Service(ServiceConfigProperties configProps) {
this.skipCheck = configProps.isSkipCheck();
}
}
@Component
public class Service {
private boolean skipCheck;
private ServiceConfigProperties configProps;
public Service(ServiceConfigProperties configProps) {
this.configProps= configProps;
}
@PostConstruct
public void initConfig() {
this.skipCheck= configProps.isSkipCheck();
}
}
Upvotes: 1
Views: 982
Reputation: 33
Never use @PostConstruct it gets completly bugged deppending how you customized your spring boot settings (thread pool, persistance datasource etc...). You should use ApplicationEvent< ApplicationReady> instead
Upvotes: 0
Reputation: 10716
With a couple of caveats, interacting with constructor-injected beans inside the constructor is completely safe.
Upvotes: 1