1.Spring 的 ApplicationListener 接口
借助Spring监听接口为数据库初始化数据,代码如下
借助Spring容器是个很好的解决方案。Spring框架提供了事件机制,而事件机制必须实现ApplicationListener监听器,因此我们只要编写一个实现类实现该接口的onApplicationEvent方法,在方法体中检测数据库的初始化数据是否存在并选择初始化之。
步骤:
1、实现ApplicationListener接口
2、交给Spring管理
3、ok!
@Repository
public class ApplicationListenerImpl implements ApplicationListener {
private StudentMapperExt studentMapperExt;
public StudentMapperExt getStudentMapperExt() {
return studentMapperExt;
}
@Resource //采用set方式获取对象,不能采用autowire,项目启动时未初始化完成spring对象
public void setStudentMapperExt(StudentMapperExt studentMapperExt) {
this.studentMapperExt = studentMapperExt;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
List<Student> studentList = studentMapperExt.selectAll();
System.out.println("studentList:" + studentList.size());
}
}
2.实现InitializingBean接口
大体思路:
1:自定义类实现InitializingBean接口
2:并追加注解@Component
3:set方法注入mapper
4:从数据库查出的数据放入map中
5:页面配置要改变的数据,修改后刷新map中的值,动态更新缓存数据
/**
* @description: TestPropertiesInit 属性数据初始化:
* 实现InitializingBean接口,重写方法afterPropertiesSet()方法,可以在项目启动时进行加载
* @author:
* @create: 2020.2.25
*/
@Component("TestPropertiesInit")
public class TestPropertiesInit implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(TestPropertiesInit.class);
//项目启动加载数据存入map中
public static Map<String, Object> map = new HashMap<String, Object>();
public static Map<String, Object> getMap() {
return map;
}
public static void setMap(Map<String, Object> map) {
TestPropertiesInit.map = map;
}
private StudentMapperExt studentMapperExt;
public StudentMapperExt getStudentMapperExt() {
return studentMapperExt;
}
@Resource //采用set方式获取对象,不能采用autowire,项目启动时未初始化完成spring对象
public void setStudentMapperExt(StudentMapperExt studentMapperExt) {
this.studentMapperExt = studentMapperExt;
}
@Override
public void afterPropertiesSet() throws Exception {
logger.info("----初始化系统参数开始---------------start");
List<Student> studentList = this.studentMapperExt.selectAll();
for (Student student : studentList) {
map.put(student.getName(), student.getId());
}
System.out.println("map=====" + map.toString());
logger.info("----初始化系统参数结束--------success-------end" + map.toString());
}
}