陌生的spring
随着工作的年限增加,逐渐接触到spring的一些可扩展的用法。之前可能只停留在@Controller @Autowired @Mapper @Service几个注解,就能在日常的项目进行愉(Ctrl C)快(Ctrl V)的CRUD操作了。
做个记录:不管是读别人代码,还是后期自己用应该能用到。
本篇帖子代码的gitee链接:spring-just-know · goahead/article-juejin - 码云 - 开源中国 (gitee.com)
由于spring boot3已经发布,故示例代码基于:jdk17 + spring boot3
后续工作中遇到新的再补充,也希望同行多多指导其他优秀实践以及对文章中的错误不吝指出
场景1:如何在项目启动后做一些初始化工作?
你可能需要:在应用启动后做Redis缓存预热,做一些配置加载等
方式1:实现CommandLineRunner
@SpringBootApplication
public class SpringJustKnowApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringJustKnowApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
log.info("do something after application started, implement by CommandLineRunner");
}
}
该方式,其实通过阅读spring的入口run方法[不停的点击run方法即可]可以很快的就能读到:
方式2:监听应用启动完成事件@EventListener(ApplicationStartedEvent.class)
@EventListener(ApplicationStartedEvent.class)
public void userCacheInit() {
log.info("do something after application started, implement by EventListener");
}
该方式基于事件,其实Spring已经内置了很多事件,应用启动完成只是一个,大家可以点击这个类进去后会发现,spring对应用启动声明周期不同阶段都提供了事件,我们可以灵活的处理:
方式3:使用@PostConstruct
@PostConstruct
public void configDone() {
log.info("do something after application started, implement by PostConstruct");
}
该方式:依赖的是Bean的组装,其实它不是严格在应用启动完成后加载,它是在Bean组装完成后就会执行。
场景2:如何在Bean工厂组装前做一些初始化工作?
比如:你需要在spring bean组装对象之前,先做一些配置[比如数据库密码,redis密码或项目组自定义的配置]解密的动作。
方式1:[不推荐] 基于手动的方式调用ApplicationContextInitializer
其他的代码请自行git clone代码哈
public static void main(String[] args) {
// 不推荐,仅仅为了演示addInitializers用法
SpringApplication application = new SpringApplication(SpringJustKnowApplication.class);
application.addInitializers(new EnvConfigDecryptInitializer());
application.run(args);
// 还是推荐下边这个spring脚手架生成的代码,简洁
// SpringApplication.run(SpringJustKnowApplication.class, args);
}
方式2:[推荐] 基于spring的SPI机制,在META-INFO/spring.factories里边声明
spring启动时会通过spi的方式,默认加载/META-INFO/spring.factories里边的东西,里边不止initial,还有autoconfigure等,具体大家可以百度下资料,很多时候项目组也有同事会基于这个写一些公共东西,大家要知道哈,不然就找不到了,一脸懵逼。
org.springframework.context.ApplicationContextInitializer=com.goahead.springjustknow.initializer.EnvConfigDecryptInitializer
场景3:Bean的注入还有好多姿势
todo: 后续补充下