第二十周_R-Spring 在项目启动时执行的方式

92 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 2 天,点击查看活动详情

在一次学习多数据源搭建的时候,看到 AbstractRoutingDataSource 实现了 InitializingBean#afterPropertiesSet 可以在项目初始化的时候就运行。以前也了解到 @PostConstruct 也能初始化数据。所以详细的学习学习。

项目启动时初始化操作:

@PostConstruct

简介

@PostConstruct 注解是 Java 提供的注解:javax.annotation.PostConstruct;

该注解被用来修饰一个非静态的 void 方法。被 @PostConstruct 修饰的方法只会被服务器执行一次。

使用场景

如果想在生成对象的时候完成某些初始化操作,但是这些操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用 @PostConstruct 注解一个方法实现。此注解注解的方法会在依赖注入完成后被自动调用。

    @Autowired
	private XxxMapper xxxMapper;

//依赖注入后,会自动调用
	@PostConstruct
    public void postConstruct(){
        xxxMapper.doService();
        System.out.println("在项目启动时:@PostConstruct 先初始化");
    }

InitializingBean

  • 必须是 BeanFactory 设置完所有属性以后才执行
  • 其次,实现此接口的必须要是一个 ioc 容器的 bean

AbstractAutowireCapableBeanFactory#invokeInitMethods() :

在依赖注入完成的时候,spring 会去检查 bean 是否实现了 InitializingBean 接口,已实现就会去调用这个类的 afterPropertiesSet 方法

@Configuration
    public class InitializeBeanTest implements InitializingBean {

        @Override
        public void afterPropertiesSet() throws Exception {
            System.out.println("InitializingBean#afterPropertiesSet 同样先初始化");
        }

    }

实现两种接口

项目中遇到调用 jar 包就会去处理逻辑,不是平常所使用的接口调用。那么此时 java -jar xxx.jar 后会直接运行逻辑。一般使用下面的两种方式都可。

ApplicationRunner

@Configuration
    public class ApplicationRunnerTest implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) {
            System.out.println("在项目启动时:实现了 ApplicationRunner#run 方法先初始化");
        }
    }

CommandLineRunner

@Configuration
public class CommandLinerTest implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("在项目启动时:实现了 CommandLineRunner#run 方法先初始化");
    }

}

事件机制

两种实现方式:

  • 注解@EventListener
  • 实现 ApplicationListener

ApplicationListener

@Component
    public class ApplicationListenerTest implements ApplicationListener<ContextRefreshedEvent> {
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            System.out.println("实现 ApplicationListener 接口初始化:"+event.getTimestamp());
        }
    }

EventListener

直接在启动类中加入

@EventListener
    public void deploymentVer(ApplicationReadyEvent event) {
        System.out.println("上下文已经准备完毕的时候触发>>>");
}

总结

目前我使用过的项目中使用的是 PostConstruct 注解和 实现 CommandLineRunner 接口的方法。