容器启动自定义方法
这个在日常工作中经常会用到,就是在Spring容器启动的时候,执行一下我们需要执行的初始化方法。
实现InitializingBean接口
@Component
public class InitMethod implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("实现InitializingBean接口");
}
}
这种方法是最常见的,之前在源码中也看过了,初始化的时候会调用这个这个接口。
实现BeanPostProcessor接口
@Component
public class InitBeanPostProcessor implements BeanPostProcessor {
private volatile int flag = 1;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (flag > 2){
return bean;
}
flag++;
System.out.println("before:实现BeanPostProcessor接口");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (flag > 2){
return bean;
}
flag++;
System.out.println("after:实现BeanPostProcessor接口");
return bean;
}
}
这种方法就是实现自己的后置处理器,需要注意的是这种方式会被调用多次,当然你也可以实现更加具体的后置处理器,这样被调用的次数会少一些。
添加PostConstruct注解
@Component
public class InitPostConstruct {
@PostConstruct
public void init(){
System.out.println("添加PostConstruct注解实现");
}
}
实现ApplicationContextAware接口
@Component
public class InitApplicationContext implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("实现ApplicationContextAware接口");
}
}
上面四种方式是Spring容器自带的。
实现InitApplicationRunner接口
@Component
public class InitApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("实现ApplicationRunner接口");
}
}
实现CommandLineRunner接口
@Component
public class InitCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("实现CommandLineRunner接口");
}
}
上面两种是SpringBoot提供的方式。
实现ServletContextAware接口
@Component
public class InitServletContextAware implements ServletContextAware {
@Override
public void setServletContext(ServletContext servletContext) {
System.out.println("实现ServletContextAware接口");
}
}
这个是spring web容器提供的方法。
实现ServletContextListener接口
@Component
public class InitServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("实现ServletContextListener接口");
}
}
这个是servlet容器提供的方法,其实和spring没有任何关系了,只是功能相似所以也写出来了。
上面八种方式的执行顺序是这样的: