Spring监听器(不同于javaweb监听器)
为什么使用Spring的监听器:在建表过程中,需要通过logService执行建表操作,所以使用Spring监听器更容易从IOC容器中获取logService的bean的实例
实现Spring监听器的步骤
1、创建一个类实现org.springframework.context.ApplicationListener<E>接口
Tips:泛型处可以传入ContextRefreshedEvent类型,针对IOC容器刷新事件进行监听。
2、实现接口中的void onApplicationEvent(E event);抽象方法
在抽象方法中判断event对象是否是org.springframework.context.event.ContextRefreshedEvent类型,如果是这个类型,则表明IOC容器创建了。
/**
* 监听器,监听项目启动IOC容器创建,则生成当月的用于保存日志的数据库表
* @author dongdong
* ApplicationListener<ContextRefreshedEvent>泛型传入ContextRefreshedEvent,证明是针对IOC容器刷新事件进行监听
*/
public class SurveyInitListener implements ApplicationListener<ContextRefreshedEvent>{
@Autowired
private LogService logService;
public void onApplicationEvent(ContextRefreshedEvent event) {
//生成当月的数据库表名
String tableName = DataProcessUtils.createTableName(0);
//绑定数据源对应的键以便选择数据源
RouterToken.bindToken(RouterToken.DATASOURCE_LOG);
//根据表明创建当月的数据表
logService.createTable(tableName);
//生成下个月的数据表名
//因为石英调度是每月15号自动建下个月的表,所以如果项目是某个月的15号以后启动的话就不会有下个月的表,
//所提每回项目启动时自动创建出下个月的表
tableName = DataProcessUtils.createTableName(1);
//绑定数据源对应的键以便选择数据源
RouterToken.bindToken(RouterToken.DATASOURCE_LOG);
//根据表名建下个月的数据表
logService.createTable(tableName);
}
}
3、关于两个IOC容器监控的问题(将监听器的bean配置在SpringMvc的配置文件里)
<!-- 配置Spring监听器:如果配在Spring配置文件中会监听两次 (用来检测IOC容器创建,IOC容器创建则建本月和下月的日志表)-->
<bean id="surveyInitListener" class="com.atguigu.survey.listener.SurveyInitListener" />
Spring 和 Spring-MVC整合注意事项
Spring MVC 和 Spring 整合的时候,SpringMVC的springmvc.xml文件中 配置扫描包,不要包含 service的注解,Spring的applicationContext.xml文件中 配置扫描包时,不要包含controller的注解,如下所示:
1.SpringMVC的xml配置:
<context:component-scan base-package="com.insigma">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
Spring MVC启动时的配置文件,包含组件扫描、url映射以及设置freemarker参数,让spring不扫描带有@Service注解的类。为什么要这样设置?因为springmvc.xml与applicationContext.xml不是同时加载,如果不进行这样的设置,那么,spring就会将所有带@Service注解的类都扫描到容器中,等到加载applicationContext.xml的时候,会因为容器已经存在Service类,使得cglib将不对Service进行代理,直接导致的结果就是在applicationContext 中的事务配置不起作用,发生异常时,无法对数据进行回滚。以上就是原因所在。
2.同样的在Spring的xml配置如下:
<context:component-scan base-package="com.insigma">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>