SpringBoot 应用 在服务启动后进行初始化工作

目录

1、在SpringBoot应用启动后进行初始工作的意义

2、如果实现在应用启动后进行初始化操作

3、实践截图


1、在SpringBoot应用启动后进行初始工作的意义

    在你的SpringBoot项目启动后,需要写入缓存,或者需要初始常量信息,此时需要使用到在SpringBoot Runner,实现其功能。

2、如果实现在应用启动后进行初始化操作

     Springboot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner

    此两种方法是为了满足,在项目启动的后,立刻执行某些方法。

   我们可以通过实现ApplicationRunner和CommandLineRunner,它们都是在SpringApplication 执行之后开始执行的。

CommandLineRunner 接口提供的方法只能传递字符串,ApplicationRunner 是使用ApplicationArguments 用来接收参数的,此方式可以自更加复杂场景使用。

使用CommandLineRunner来实现启动后执行

/**
 * ApplicationRunner
 * 该接口的方法会在服务启动之后被立即执行
 * 主要用来做一些初始化的工作
 * 但是该方法的运行是在SpringApplication.run(…​) 执行完毕之前执行
 */
@Component
public class LoadConstantsAndWriteCacheRunner implements CommandLineRunner {

    /**
     * 会在服务启动完成后立即执行
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("This will be execute when the project was started!");
    }
}

 通过 ApplicationRunner实现的接口

@Component
public class LoadConstantsAndWriteCacheRunner implements ApplicationRunner {
    /**
     * 会在服务启动完成后立即执行
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
     System.out.println("ApplicationRunner will be execute when the project was started!");
    }
}

这两种方式的实现都很简单,直接实现了相应的接口就可以了。记得在类上加@Component注解。

如果想要指定启动方法执行的顺序,可以通过实现

org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解来实现。

建议使用 Order注解实现方式

/**
 * 此类是将spring配置信息转换成静态属性
 */
@Component
@Order(value = 1) 
public class LoadConstantsAndWriteCacheRunner implements ApplicationRunner {
	public static String appKey;
	
	@Autowired
	private FrameworkBaseConfig frameworkBaseConfig;
	
	@Autowired
	private RedisStringService redisStringService;
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		/**
		System.out.println("ApplicationRunner: "+frameworkBaseConfig.getAppKey());
		appKey = frameworkBaseConfig.getAppKey();
		*/
		System.out.println("ApplicationRunner: "+frameworkBaseConfig.getAppKey());
		appKey = frameworkBaseConfig.getAppKey();
		redisStringService.set("systemNameServletWrite", "whdcmap-web");
		System.out.println("ApplicationRunner initCache function!");		
		System.out.println("ApplicationRunner DIC_KEY:"+CacheRedisConstants.REDIS_KEYS.DIC_KEY);
	}	
}

3、实践截图

    本人主要目的是想在系统启动完毕后实现数据字典及常量配置参数表写入到Redis缓存之中。实现如下图所示:

参考文章:

Spring Boot--项目启动时执行特定方法 

Springboot Runner - 在服务启动后进行初始化工作

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值