Spring Boot 2 - @Component loading before @Configuration

2.2k Views Asked by At

I have a Spring Boot Application and two classes that come from different jars that i am using, where one of them is @Component, and the other one is @Configuration.
Both of them have @PostConstruct methods and basically here is my use case -> i want the @Configuration's @PostConstruct to run before @Component's @PostConstruct. Is it possible to achieve this somehow?
I tried with @DependsOn on the @Component (referencing the @Configuration - which does not have any beans inside - only @PostConstruct), but it does not work.
Here are code pieces.
First file:

@Configuration
public class MainConfig {
    @PostConstruct
    public void postConstruct() {
        // doSomething
    }
}

Second file.

@Component
public class SecondClass {
  @PostConstruct
  public void init() throws InterruptedException {
    // doSomething that depends on postConstruct from MainConfig
  } 
}

Thanks a lot in advance

1

There are 1 best solutions below

3
On BEST ANSWER
@Configuration
public class MainConfig {

    public void postConstruct() {
        // doSomething
    }
}


@Component
public class SecondClass {

  @Autowired
  private MainConfig mainConfig;

  @PostConstruct
  public void init() throws InterruptedException {
    mainConfig.postConstruct();
    // doSomething that depends on postConstruct from MainConfig
  } 
}