背景
在spring开发中,经常要有一些初始化操作,经常纠结与初始化时的执行顺序,对于需求的理解,不知道什么时候什么时候被执行才是正确的。
分析
在服务启动时若要加载一些服务配置,如数据库配置,系统配置。springBoot 提供了ApplicationRun和CommandLineRunner,Spring提供了InitializingBean,Jdk提供了@PostConstruct。
CommandLineRunner和ApplicationRunner的作用是相同的。
不同之处在于CommandLineRunner接口的run()方法接收String数组作为参数,即是最原始的参数,没有做任何处理;而ApplicationRunner接口的run()方法接收ApplicationArguments对象作为参数,是对原始参数做了进一步的封装。
当程序启动时,我们传给main()方法的参数可以被实现CommandLineRunner和ApplicationRunner接口的类的run()方法访问,即可接收启动服务时传过来的参数。我们可以创建多个实现CommandLineRunner和ApplicationRunner接口的类。为了使他们按一定顺序执行,可以使用@Order注解或实现Ordered接口。
@Component
public class Test implements InitializingBean, ApplicationRunner, CommandLineRunner {
@PostConstruct
public void init(){
System.out.println("PostConstruct 方法执行");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean 方法执行");
}
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("这个是测试ApplicationRunner接口");
}
@Override
public void run(String... args) throws Exception {
System.out.println("这个是测试CommandLineRunn接口");
}
}
@PostConstruct>InitializingBean>ApplicationRunner>CommandLineRunner
servlet在启动时会执行@PostConstruct修饰的方法,该方法只会执行一次,在构造方法之后,但在init() 方法之前
服务启动加载servlet--> servlet加载类的构造方法--> @AutoWired注解-->@PostConstruct注解-->init()方法-->service-->destroy()-->@ProDestroy-->服务器卸载servlet
执行顺序
@PostConstruct
InitializingBean
@EventListener(ApplicationStartedEvent.class)
ApplicationRunner/CommandLineRunner
@EventListener(ApplicationReadyEvent.class)
bean实现Aware
Aware 简介
Spring中提供了一些以Aware结尾的接口,实现了Aware接口的bean在被初始化之后,可以获取相应资源。比如BeanNameAware之类的以Aware结尾的接口,这个接口获取的资源就是以BeanName相关的。
通过Aware接口,可以对Spring相应资源进行操作(一定要慎重,因为获取的资源可能是IOC的核心资源)。
为对Spring进行简单的扩展提供了方便的接口。
ApplicationContextAware会向实现了这个接口的Bean提供ApplicationContext,也就是IOC容器的上下文的信息。当然,实现了这个接口的Bean必须配置到bean的配置文件中去,并且由Spring的Bean容器去加载,这样才能实现这样的效果。
public class MyBean implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void doSomething() {
// 获取其他的Bean实例或其他的组件
OtherBean otherBean = applicationContext.getBean("otherBean", OtherBean.class);
// ...
}
}
本文在记录时参考下列博主:
转载
原文链接:https://blog.csdn.net/mahl1990/article/details/122616240
转载
原文链接:https://blog.csdn.net/qq_52988841/article/details/132154054