ssm 自定义aop不生效 不执行

 

在s

sm里自己写了个aop切面,通过注解配置,发现不生效,最后找到原因,是spring配置时,只扫描了controller和service,并没有扫描aop类

applicationContent。xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:aop="http://www.springframework.org/schema/aop"  
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	           http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
			   http://www.springframework.org/schema/context
	           http://www.springframework.org/schema/context/spring-context-4.2.xsd
	           http://www.springframework.org/schema/tx
	           http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
	           http://www.springframework.org/schema/aop
	           http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
	           http://www.springframework.org/schema/jdbc 
	           http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
	    
	           ">
<!-- <context:component-scan base-package="com.sunny" />
 -->	
 <context:component-scan base-package="com.sunny">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Service" />
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
 <!-- 加载资源文件 其中包含变量信息,必须在Spring配置文件的最前面加载,即第一个加载 -->
	<context:property-placeholder location="classpath:persistence-jdbc.properties" />
  
	 
	<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">  
        <property name="poolProperties">  
            <bean class="org.apache.tomcat.jdbc.pool.PoolProperties">  
                <property name="url" value="${jdbc.url}"/>  
                <property name="driverClassName" value="${jdbc.driver}"/>  
                <property name="username" value="${jdbc.username}"/>  
                <property name="password" value="${jdbc.password}"/>  
                <property name="jmxEnabled" value="true"/>  
                <property name="testWhileIdle" value="false"/>  
                <property name="testOnBorrow" value="true"/>  
                <property name="validationInterval" value="30000"/>  
                <property name="testOnReturn" value="false"/>  
                <property name="validationQuery" value="select 1"/>  
                <property name="timeBetweenEvictionRunsMillis" value="30000"/>  
                <property name="maxActive" value="50"/>  
                <property name="maxIdle" value="10"/>  
                <property name="initialSize" value="20"/>  
                <property name="maxWait" value="10000"/>  
                <property name="removeAbandonedTimeout" value="60"/>  
                <property name="minEvictableIdleTimeMillis" value="30000"/>  
                <property name="minIdle" value="10"/>  
                <property name="logAbandoned" value="true"/>  
                <property name="removeAbandoned" value="true"/>  
                <property name="jdbcInterceptors" value="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"/>  
            </bean>  
        </property>  
    </bean>  
	
	
	  <bean id="jdbcTemplate"  class="org.springframework.jdbc.core.JdbcTemplate" abstract="false"
        lazy-init="false" autowire="default" >
        	<property name="dataSource" ref="dataSource" />
    </bean>

	<!-- ========================================分隔线========================================= -->
	<!-- 配置Spring的事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 -->
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
		<property name="mapperLocations" value="classpath*:/com/sunny/model/mapper/*.xml" />
	</bean>	
	
	
	<bean id="log4jdbcInterceptor" class="net.sf.log4jdbc.DataSourceSpyInterceptor" />
	<bean id="interceptorTest" class="framework.InterceptorTest" />
	<bean id="dataSourceLog4jdbcAutoProxyCreator" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="interceptorNames">
			<list>
				<value>log4jdbcInterceptor</value>
			</list>
		</property>
		<property name="beanNames">
			<list>
				<value>dataSource</value>
			</list>
		</property>
	</bean>
	

  <!-- 开启shiro注解-->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
          depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true" />
    </bean>

    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
 
	
		
	<!-- 配置通知  暂时未启用 -->
<!-- 	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="add*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
			<tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
		</tx:attributes>
	</tx:advice> -->
	
	<!-- 配置切面  暂时未启用-->
<!-- 	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.sunny.service.impl.*.*(..))"/>
	</aop:config> -->	

</beans>	

 

 

init-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	           http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
			   http://www.springframework.org/schema/context
	           http://www.springframework.org/schema/context/spring-context-4.2.xsd
	           http://www.springframework.org/schema/tx
	           http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
	           http://www.springframework.org/schema/aop
	           http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
	           http://www.springframework.org/schema/mvc  
      		   http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
	<!-- 启动自动扫描 该包下所有的Bean(@Controller) -->
	<context:component-scan base-package="com.sunny" />
<!-- 扫描aop的包  -->
	<context:component-scan base-package="framework.aop" />
	
	<context:annotation-config />
	<!-- 配置织入@Aspectj切面  -->
	<aop:aspectj-autoproxy proxy-target-class="true" />
	
	<mvc:interceptors>
           		 <bean class="framework.interceptors.UserSessionInterceptor"></bean>
	 </mvc:interceptors>
	
	<!-- mvc 配置 自动配置一些默认设置和注解驱动 -->
	<mvc:annotation-driven />
	<!-- 对于一些静态资源的设置 -->
	<mvc:default-servlet-handler />

<!-- ============================== springframework.web.servlet.view ============================== -->
	<bean class="org.springframework.web.servlet.view.BeanNameViewResolver"  >
	 <property name="order" value="0" />
	</bean>

	<!-- 根据客户端的不同的请求决定不同的 view进行响应, 如 /blog/1.json /blog/1.xml -->
	<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver"  >
		 
		<property name="viewResolvers">
			<list>
				<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
					<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
					<property name="contentType" value="text/html" />
					<property name="prefix" value="/jsp" />
					<property name="suffix" value=".jsp" />
				</bean>
			</list>
		</property>
		 <property name="order" value="1" />
	</bean>

	<!-- 默认的视图解析器 在上边的解析错误时使用 (默认使用html)- -->
	<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		<property name="contentType" value="text/html" />
		<property name="prefix" value="/WEB-INF/pages" />
		<property name="suffix" value=".jsp" />
		 <property name="order" value="2" />
	</bean>

	<!-- json view -->
	<bean id="defaultJsonView" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView" />

	<!-- 上传文件的最大尺寸为100MB,maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="104857600" />
		<property name="maxInMemorySize" value="40960" />
	</bean>
	<!-- 在超出上传文件限制时的跳转页面,此时还没有进入到Controller方法中 -->
	<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/front/errorUploadSize</prop>
			</props>
		</property>
	</bean>
	
 

	<!-- 定义视图解析器 -->
	<!-- <bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean> -->


	 <!-- 全局异常处理器 -->
	<!--<bean class="com.sunny.exception.ExceptionResolver"></bean> -->
</beans>	
package framework.aop;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class WxUserDzUserUpdateAspect {

	private static final Log logger = LogFactory.getLog(WxUserDzUserUpdateAspect.class);

	/**
	 * 对注释有RequestMapping标记的方法,进行AOP切入拦截
	 */
	@Pointcut(" execution (* com.sunny.service.impl..*.*(..))")
	public void controllerPointcut() {

	}

	@After(value="controllerPointcut()")
	public void after(JoinPoint joinPoint) {
		System.out.println("---------------------------joinPoint");

	}

	@SuppressWarnings("unchecked")
	@Around("controllerPointcut()  ")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		System.out.println("---------------------------joinPoint");
		return joinPoint.proceed(joinPoint.getArgs());
	}

	/**
	 * 异常统一处理
	 * 
	 * @Title: afterThrowing
	 * @Description:
	 * @author weifa.Yang
	 * @date 2016-8-3 下午04:19:57
	 * @param e
	 * @return void
	 */
	@AfterThrowing(pointcut = "controllerPointcut() ", throwing = "e")
	public void afterThrowing(JoinPoint joinPoint, Throwable e) {
		logger.error("展客[RPC],请求接口[" + joinPoint.getTarget().getClass().getName() + "],方法[" + joinPoint.getSignature().getName() + "],方法抛出异常:" + e.getMessage());
	}

	/**
	 * 返回值日志记录
	 * 
	 * @Title: afterReturning
	 * @Description:
	 * @author weifa.Yang
	 * @date 2016-8-3 下午04:20:05
	 * @param joinPoint
	 * @param result
	 * @return void
	 */
	@AfterReturning(pointcut = "controllerPointcut() ", returning = "result")
	public void afterReturning(JoinPoint joinPoint, Object result) {
		logger.info("响应展客[RPC]接口[" + joinPoint.getSignature().getName() + "],返回结果:");
	}
}

添加扫描后 ,可以执行了

但是这样有个隐患,就是springmvc配置了全路径扫描,而不是最正确的只扫描controller,这就会导致没有事务增强,所以我就改成init-servlet。xml只扫描controller,结果这样导致aop无法生效。

原因是,Service的扫描在spring容器内,而不是在springmvc子容器内,配置aop应该在application。xml里,在里面加上        <aop:aspectj-autoproxy proxy-target-class="true"/>   开启aop就可以了

 

转载于:https://my.oschina.net/u/1423640/blog/888966

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值