如果只是想让类A早于B进行加载,这种就简单了,基于spring的加载机制,可以有两种方式实现方式:
①基于@DependsOn注解的形式,在B类中添加注解,
②基于IOC原理,内部依赖会早于该类进行实例化,在B类中依赖A
如果是想在所有类之前加载可以实现BeanDefinitionRegistryPostProcessor接口
如果是想在类加载之后加载某个类或者执行某个操作,可以
①实现ApplicationListener接口,监听ApplicationReadyEvent 事件
@Component
public class MyListener implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
// doSomething
}
}
②使用注解@EventListener
@EventListener(ApplicationReadyEvent.class)
public void doSomething() {
//do something
}
③使用@PostConstruct
@Component
public class TestAnoEvent {
@PostConstruct
public void doSomething() {
//do something
System.out.println("PostConstruct ----- doSomething");
}
}
④实现CommandLineRunner
@Component
public class TestCommandLiner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("TestCommandLiner ----- doSomething");
}
}
⑤实现ApplicationRunner
@Component
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("TestApplicationRunner ----- doSomething");
}
}