1. 说明
-
执行顺序
-
实现ServletContextListener---contextInitialized -
实现 ServletContextAware -
静态代码块 -
@PostConstruct -
实现ApplicationRunner -
实现CommandLineRunner
-
-
说明
Spring中很特殊的类,Spring启动时可自动运行。xxxxAware BeanDefinitionRegistryPostProcessor // 在spring容器加载了bean的定义文件之后,在bean实例化之前执行的。 // 接口方法的入参是ConfigurrableListableBeanFactory, // 使用该参数,可以获取到相关bean的定义信息 BeanFactoryPostProcessor // 带了 Post 一般都是什么之后 // 后置处理器,初始化 Bean 前后进行处理工作,将后置处理器加入到容器中 // 一般用来给 bean 动态加载一些其他的数据 // 比如请求查询其他程序接口动态加载 bean BeanPostProcessor
2. 执行代码
-
实现
ServletContextListener接口/** * 在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化。 */ @Component public class Test01 implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("实现ServletContextListener---contextInitialized"); } } -
实现
ServletContextAware接口,重写setServletContext方法该方法会在
填充完普通 Bean 的属性,但是还没有进行Bean的初始化之前执行/** * 在填充普通bean属性之后但在初始化之前调用 * 类似于initializingbean的afterpropertiesset或自定义init方法的回调 * */ @Component public class Test02 implements ServletContextAware { @Override public void setServletContext(ServletContext servletContext) { System.out.println("实现 ServletContextAware"); } } -
将要执行的方法所在的类交给
spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解,或者静态代码块执行。@Component public class Test03 { // 静态代码块会在依赖注入后自动执行,并优先执行 static { System.out.println("---static--"); } /** * PostConstruct 注解在依赖注入完成后自动调用 */ @PostConstruct public static void test() { System.out.println("@PostConstruct在依赖注入完成后自动调用"); } } -
实现
ApplicationRunner接口/** * 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个Applicationrunner bean * 在同一应用程序上下文中,可以使用有序接口或@order注释对其进行排序。 */ @Component public class Test04 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("实现ApplicationRunner"); } } -
实现
CommandLineRunner接口/** * 用于指示bean包含在SpringApplication中时应运行的接口。可以在同一应用程序上下文中定义多个commandlinerunner bean,并且可以使用有序接口或@order注释对其进行排序。 * 如果需要访问applicationArguments而不是原始字符串数组,请考虑使用applicationrunner。 * */ @Component public class Test05 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("实现CommandLineRunner"); } }
本文深入探讨了Spring中不同类型的初始化回调和执行顺序,包括ServletContextListener、ServletContextAware、@PostConstruct、ApplicationRunner和CommandLineRunner的用法。通过示例代码展示了它们在Spring启动时的运行流程,帮助理解Spring容器初始化阶段的各种回调机制。
1790

被折叠的 条评论
为什么被折叠?



