如何让一个类提前加载

        如果只是想让类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");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值