3

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

alext
  • 678
  • 1
  • 11
  • 25

1 Answers1

2
@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
  } 
}
Mykhailo Skliar
  • 1,242
  • 1
  • 8
  • 19
  • this is not the same, you just trigger a method in a different place here, of course. – Eugene Jun 01 '21 at 18:08
  • this solved my issue, basically if u Autowire the config Spring will initialize the Config before calling PostConstruct on the SecondClass Method. I also found another way to solve this, i added the package of the main config to the ComponentScan of my application, which also worked – alext Jun 01 '21 at 18:13
  • 1
    @AleksandarT I wouldn't rely on the ordering of the spring post-construct methods, unless it is explicitly guaranteed by spring documentation. It might worked in your case, but could be different in production environment, or in any other version of spring or java. – Mykhailo Skliar Jun 01 '21 at 21:08