【java】【springboot】项目初始化时执行方法

一、springboot项目启动前执行方法

ApplicationStartedEvent是Spring Boot框架中的一部分,它属于ApplicationEvents,这些事件在Spring Boot应用程序的不同生命周期阶段被发布。ApplicationStartedEvent是在Spring应用上下文开始初始化之前发布的,即在所有bean定义被注册到ApplicationContext但尚未实例化任何bean之前。

@Component
public class StartupEventListener implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        // 在这里可以访问event.getArgs()获取启动参数
        // 也可以访问event.getApplicationContext()获取ApplicationContext
        // 执行启动前的初始化逻辑
    }
}

二、项目启动好后执行的代码

2、ApplicationReadyEvent

Spring Boot应用完全启动并准备好服务请求之后执行一些代码,你应该关注的是ApplicationReadyEvent,这个事件在所有的bean已经实例化并且所有的@PostConstruct和InitializingBean.afterPropertiesSet()方法都被调用之后发布。

@Component
public class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 初始化代码
    }
}

3、@PostConstruct注解

你可以在任何非静态方法上使用@PostConstruct注解,这个方法会在依赖注入完成后自动调用。但是要注意的是,@PostConstruct标记的方法不能有任何参数。

@Component
public class MyInitializer {

    @PostConstruct
    public void init() {
        // 初始化代码
    }
}

4、实现InitializingBean接口

实现Spring的InitializingBean接口,并覆盖afterPropertiesSet()方法。当Spring容器完成了bean的属性填充后,会调用此方法。

@Component
public class MyInitializer implements InitializingBean {

    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化代码
    }
}

5、使用CommandLineRunner或ApplicationRunner:

这两个接口允许你在Spring Boot应用启动后立即执行一些代码。CommandLineRunner接收命令行参数,而ApplicationRunner则可以访问ApplicationArguments。

@Component
public class MyInitializer implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        // 初始化代码
    }
}

6、在配置类中使用@Bean方法:

如果初始化逻辑与某个特定的bean相关联,你可以在配置类中定义一个@Bean方法来处理初始化逻辑。

@Configuration
public class MyConfig {

    @Autowired
    private SomeService someService;

    @Bean
    public SomeOtherService someOtherService() {
        SomeOtherService service = new SomeOtherService();
        service.setSomeService(someService);
        service.init(); // 假设SomeOtherService有一个init方法
        return service;
    }
}

7、监听ApplicationEvent事件:

使用Spring的事件机制,监听ApplicationReadyEvent,这个事件在Spring Boot应用完全启动后触发。

@Component
public class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // 初始化代码
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值