当需要在项目启动时进行一些初始化操作,.例如初始化数据库、读取数据库加入缓存等,有以下几种方式。
-
ApplicationRunner/CommandLineRunner接口
接口描述:
* Interface used to indicate that a bean should <em>run</em> when it is contained within
* a {@link SpringApplication}. Multiple {@link ApplicationRunner} beans can be defined
* within the same application context and can be ordered using the {@link Ordered}
* interface or {@link Order @Order} annotation.
接口表示当一个bean被加入一个容器中时执行其run方法。多个bean可以被定义在一个spring context中,可以使用ordered接口或者@Order注解排序
两个接口大同小异,只是接受的参数不同。
CommandLineRunner接受的是最原始的参数,ApplicationRunner的参数是ApplicationArguments args,是对原始参数的进一步封装,可以通过name来获取value

提供对用于启动一个spring应用参数的访问。

-
InitializingBean接口
接口描述:
/**
* Interface to be implemented by beans that need to react once all their
* properties have been set by a BeanFactory: for example, to perform custom
* initialization, or merely to check that all mandatory properties have been set.
*/
当一个Bean在被BeanFactory设置完全部属性后需要做出某种动作时,可以实现这个接口。比如执行自定义的初始化操作,或者检查所有必须的属性是否被设置。
-
使用事件监听 ApplicationEvent/ApplicationListener
ContextRefreshedEvent 这个事件:
/**
* Event raised when an {@code ApplicationContext} gets initialized or refreshed.
*/
当一个ApplicationContext被初始化或者刷新的时候该事件被发起。
写一个Bean实现ApplicationListener<ContextRefreshedEvent >,监听applicationcontext的初始化,处理业务
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//业务处理
}
网友评论