1

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.

  • Is it unsafe to work with beans in constructor in that case?

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();
    }   
}

1 Answers1

1

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

crizzis
  • 9,978
  • 2
  • 28
  • 47