項目啟動的時候有時候需要加載一些項目配置資料如網站位址,發送短信,郵件的發件人使用者名密碼等config資料,或者是系統的錯誤碼提示資料等。可通過配置ApplicationListener的實作類來實作;
@Component
public class DataSourceInitListener implements ApplicationListener<ContextRefreshedEvent> {//ContextRefreshedEvent為啟動事件
private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceInitListener.class);
@Autowired
private SystemConfigService systemConfigService;
@Autowired
private ItemService itemService;
@Autowired
private SystemResultService systemResultService;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null) {//判斷是否執行過,執行過則不再執行
LOGGER.info("初始化systemConfig資料");
systemConfigService.initConfig();
LOGGER.info("初始化傳回消息資料");
systemResultService.initResult();
LOGGER.info("系統初始化結束...........");
}
}
}
在調用的init方法中可把這些資料儲存到redis中,
@Override
public void initConfig() {
List<SystemConfig> list = mapper.getList(new SystemConfig());
for (SystemConfig config:list) {
String key = Constant.REDIS_SYSTEM_CONFIG + config.getSystemCode();
RedisUtil.set(key, config.getSystemValue());
}
}
當需要使用這些參數時,根據具體的key通過調用redis的get方法,就可以把參數具體的值取出;