很多同学在使用ssm框架中,可能会用到项目启动便要加载的一些类,由于不像springboot,有直接封装的注解便可实现,但是它也有自己的实现方式,具体如下:
@Component
public class RedisCeshiController implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次
try {
start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
通过实现ApplicationListener类,并且重写它里面的onApplicationEvent方法,将你要加载的代码写到start方法里面即可,记得Component注解必须要加,