当前位置: 首页 > 后端技术 > Java

六种方式,教你在SpringBoot初始化时搞点事情

时间:2023-04-01 14:45:57 Java

六种方法教你在SpringBoot初始化时做一些事情那么经典的问题就来了,这也是面试官经常问的问题:SpringBoot项目启动时做一些事情的方法有哪些?方法有很多,下面介绍几个常用的方法。1、监听容器刷新完成的扩展点ApplicationListenerApplicationContext事件机制是通过观察者设计模式实现的,ApplicationContext的事件机制是通过ApplicationEvent和ApplicationListener这两个接口实现的。Spring中的一些内置事件如下:ContextRefreshedEvent:该事件在ApplicationContext初始化或刷新时发布。使用ConfigurableApplicationContext接口中的refresh()方法也可以发生这种情况。这里的初始化是指:所有Bean加载成功,后处理Bean检测激活,所有SingletonBean预实例化,ApplicationContext容器准备就绪。ContextStartedEvent:该事件在使用ConfigurableApplicationContext(ApplicationContext子接口)接口中的start()方法启动ApplicationContext时发布。您可以轮询您的数据库,或者您可以在收到此事件后重新启动任何已停止的应用程序。ContextStoppedEvent:当使用ConfigurableApplicationContext接口中的stop()停止ApplicationContext时发布此事件。您可以在收到此事件后进行必要的清理。ContextClosedEvent:当使用ConfigurableApplicationContext接口中的close()方法关闭ApplicationContext时发布此事件。一个封闭的上下文已经到了生命周期的尽头;它无法刷新或重新启动。RequestHandledEvent:这是一个特定于Web的事件,它告诉所有bean已处理HTTP请求。只能应用于使用DispatcherServlet的Web应用程序。当使用Spring作为前端MVC控制器时,系统会在Spring处理完用户请求后自动触发该事件。好了,了解了上面的内置事件后,我们就可以在SpringBoot启动时监听ContextRefreshedEvent来完成一些操作了。代码如下:@ComponentpublicclassTestApplicationListenerimplementsApplicationListener{@OverridepublicvoidonApplicationEvent(ContextRefreshedEventcontextRefreshedEvent){System.out.printn(contextRefreshedEvent);System.out.println("TestApplicationListener................");}}可以自定义高级玩法该事件实现了一些特定的需求,比如:邮件发送成功后,做一些业务处理。自定义EmailEvent,代码如下:来源);     this.address=地址;     this.text=文本;  }  //......地址和文本setter,getter}自定义监听器,代码如下:{       EmailEventemailEvent=(EmailEvent)event;       System.out.println("邮箱地址:"+emailEvent.getAddress());       System.our.println("邮件内容:"+emailEvent.getText());     }else{       System.our.println("容器本身事件:"+event);     }  }}发送邮件后触发事件,代码如下:bean.xml");     //创建ApplicationEvent对象     EmailEventevent=newEmailEvent("hello","abc@163.com","Thisisatest");     //主动触发事件     context.publishEvent(event);  }}2,SpringBoot的CommandLineRunner接口会在容器初始化后调用CommandLineRunner中的run()方法,也可以在容器启动后实现一些东西。该方法比ApplicationListener更灵活,具体如下:不同的CommandLineRunner实现可以通过@Order()指定执行顺序可以接受从控制台输入的参数。下面自定义一个实现类,代码如下:@Component@Slf4jpublicclassCustomCommandLineRunnerimplementsCommandLineRunner{/***@paramargs接收控制台传入的参数*/@Overridepublicvoidrun(String...args)throwsexception{log.debug("Receiveparametersfromtheconsole>>>>"+Arrays.asList(args));}}运行这个jar,命令如下:java-jardemo.jaraaabbbccc三个参数分别是在上面的命令中传入的,分别是aaa、bbb、ccc,这三个参数都会被run()方法接收到。如下图:源码分析,看过我文章的铁粉应该知道CommandLineRunner是如何执行的。SpringBoot加载上下文的入口在org.springframework.context.ConfigurableApplicationContext()方法中,如下图所示:该方法执行,源码如下:3.SpringBoot的ApplicationRunner接口ApplicationRunner和CommandLineRunner都是SpringBoot提供的。与CommandLineRunner相比,更好的封装了控制台传入的参数,可以通过key值来获取指定的参数,比如--version=2.1.0。此时运行jar命令如下:java-jardemo.jar--version=2.1.0aaabbbccc上面的命令传入了四个参数,一个键值对version=2.1.0,另外三个是aaa,bbb,ccc。也可以通过@Order()指定优先级,如下代码所示:{},{},{}",args.getOptionNames(),args.getNonOptionArgs(),args.getSourceArgs());}}运行上面的命令,结果如下:源码分析同上CommandLineRunner,也是在方法callRunners()中执行的,源码如下:4.前三个@PostConstruct注解是容器初始化完成后要做的一些事情。@PostConstruct注解是为了在Bean初始化完成后做一些事情,比如注册一些监听器……@PostConstruct注解一般放在Bean的方法上。Bean初始化完成后,将调用此方法。代码如下:@Component@Slf4jpublicclassSimpleExampleBean{@PostConstructpublicvoidinit(){log.debug("Bean初始化完成,调用.......");}}5.指定方法@Bean注解中的初始化方法与@PostConstruct类似。它还指定了在Bean初始化完成后要调用的方法。新建一个Bean,代码如下:@Slf4jpublicclassSimpleExampleBean{publicvoidinit(){log.debug("Bean初始化完成,调用......");}}在配置中传@classBean实例化这个Bean,但是@Bean中的initMethod属性需要指定初始化后需要执行的方法,如下:@Bean(initMethod="init")publicSimpleExampleBeansimpleExampleBean(){returnnewSimpleExampleBean();}6、InitializingBean接口InitializingBean的用法与@PostConstruct基本相同,只是对应的Bean需要实现afterPropertiesSet方法,代码如下:@Slf4j@ComponentpublicclassSimpleExampleBeanimplementsInitializingBean{@OverridepublicvoidafterPropertiesSet(){log.debug("Bean初始化完成,调用......");}}总结的实现方案很多,笔者只是总结了常用的6个,学了就喜欢。如果这篇文章对你有帮助,别忘了连打3个,点赞、转发、评论,我们下期再见!了解更多JAVA知识和技能,关注和私信博主(666)