一、启动时加载数据,就用CommandLineRunner
只需要将类实现CommandLineRunner,并且加上Component注解,还可以通过Order来控制启动顺序。
@Component
@Order(value=1)
public class MyStartupRunner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 22222222 <<<<<<<<<<<<<");
}
}
另一种方法是:实现ApplicationRunner,这两个接口中有一个run方法,我们只需要实现这个方法即可。这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。
二、Spring中Bean的生命周期
对于Singleton作用域的Bean,Spring容器将会跟踪它们的生命周期,容器知道何时实例化结束、何时销毁。Spring可以管理Bean在实例化结束之后和Bean销毁之前的行为。
Spring默认所有的Bean都是Singleton,如果是原型类型的,可以使用@Scope("prototype")
进行注解。
1、Bean依赖注入完成之后的初始化操作
有三种方式:
- 使用XML配置
在Spring配置文件中使用init-method属性:这个属性指定某个方法在Bean全部依赖关系设置结束后自动执行。这个方法写在Bean里面。使用这种方法不需要将代码与Spring耦合在一起,代码污染小,推荐使用。 - 使用注解
使用@PostConstruct
- 实现接口
让Bean实现InitializingBean接口:该接口提供了一个afterPropertiesSet() throwsException方法,在Bean里面实现它。
Spring容器会在为该Bean注入依赖关系后,调用该Bean实现的afterPropertiesSet方法。
2、Bean销毁之前的操作
- 使用destroy-method属性:指定某个方法在Bean销毁之前被自动执行。使用这种方法,不需要将代码与Spring的接口耦合在一起,代码污染小,推荐使用。
- 实现DisposableBean接口:该接口提供了一个destroy() throws Exception的方法。在Bean里面实现它,这个方法将在Bean销毁之前被Spring调用。
- 使用
@PreDestroy
注:
- PostConstruct和PreDestroy是JavaEE的内容,不是Spring的注解。