Igor Volynskiy
Igor Volynskiy

Reputation: 56

Should I never use @PostConstruct in Spring Boot when I have All Args Constructor?

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
}
  1. Can be unsafe? - but it looks better
@Component
public class Service {
    private boolean skipCheck;

    public Service(ServiceConfigProperties configProps) {
        this.skipCheck = configProps.isSkipCheck();
    }
}
  1. Can't be unsafe?
@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

Answers (2)

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

crizzis
crizzis

Reputation: 10716

With a couple of caveats, interacting with constructor-injected beans inside the constructor is completely safe.

Upvotes: 1

Related Questions