1

我有一个 Spring Boot 应用程序和两个来自我正在使用的不同 jar 的类,其中一个是 @Component,另一个是 @Configuration。
它们都有@PostConstruct 方法,基本上这是我的用例-> 我希望@Configuration 的@PostConstruct 在@Component 的@PostConstruct 之前运行。有可能以某种方式实现这一目标吗?
我尝试在@Component 上使用@DependsOn(引用@Configuration - 里面没有任何bean - 只有@PostConstruct),但它不起作用。
这是代码片段。
第一个文件:

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

第二个文件。

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

非常感谢提前

4

1 回答 1

1
@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
  } 
}
于 2021-06-01T17:59:35.960 回答