SpringBoot初始化相关操作
相关的使用场景
-
在项目中难免会遇到某些特定的数据会预先进行缓存,不管是使用Redis或者Map还是其他方式进行缓存,都需要在启动项目或者初始化Bean的时候进行数据缓存。
-
在某些特定的业务中需要在bean初始化后执行一些其他操作。
初始化方式
- 使用init-method初始化缓存,Spring原始使用是基于xml标签使用的,SpringBoot只需在注解属性指定即可
@Configuration
public class BeanConfig {
@Bean(initMethod = "init")
public ConfigServiceImpl configService(){
return new ConfigServiceImpl();
}
}
对应Bean要有指定的方法
public void init() {
log.info("------初始化配置信息-----");
//TODO 加载系统配置信息到缓存中
}
- 使用@PostConstruct 注解方法
@PostConstruct
public void init() {
log.info("------初始化配置信息-----");
//TODO 加载系统配置信息到缓存中
}
- 使用 实现CommandLineRunner接口的方式实现其run方法,在系统启动后执行此run方法
@Service
public class TestService implements CommandLineRunner {
private final static Logger log = LoggerFactory.getLogger(TestService.class);
@Override
public void run(String... args) throws Exception {
log.info("-----初始化testService------");
//TODO 加载系统配置信息到缓存中
}
}
- 使用ApplicationRunner接口
//项目启动成功首先缓存接口的信息
@Component
public class RunnerExecute implements ApplicationRunner {
private final static Logger logger = LoggerFactory.getLogger(RunnerExecute.class);
@Resource
private RedisTemplate redisTemplate;
@Resource
private ApiService apiService;
//是否开启缓存 默认true
@Value("${api.enableCache:true}")
private boolean enableCache;
@Override
public void run(ApplicationArguments args) {
if (!enableCache) {
logger.info("系统接口缓存信息未开启");
return;
}
logger.info("系统接口缓存信息已开启");
HashOperations opsForHash = redisTemplate.opsForHash();
List<Api> apiList = opsForHash.values("ApiList");
if (apiList == null) {
//保存接口信息到redis缓存
apiList = apiService.list();
Map<String, Api> apiMap = new HashMap<>();
apiList.forEach(api -> {
apiMap.put(api.getUrl(), api);
});
opsForHash.putAll("ApiList", apiMap);
}
//TODO 缓存其他信息
}
}
- 使用 InitializingBean 接口,InitializingBean 是由Spring框架提供的接口,其与@PostConstruct注解的工作原理非常类似。如果不使用注解的话,你需要让Bean实例继承 InitializingBean接口,并实现afterPropertiesSet()这个方法。
@Component
public class InitialingzingBeanTest implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("InitializingBean..");
}
}

浙公网安备 33010602011771号