注解
xml的直接配置
1 <aop:config proxy-target-class="false"> 2 //切入点 3 <aop:pointcut expression="execution(public * com.bdqn.service.*.*(..))" 4 id="myPointcut"/> 5 //切面 6 // ref增强处理类 7 <aop:aspect ref="serviceLogging"> 8 //前置增强 +切入点 9 <aop:before method="before" pointcut-ref="myPointcut"/> 10 <aop:after method="after" pointcut-ref="myPointcut"/> 11 12 <aop:after-returning method="afterReturning" returning="rt" pointcut-ref="myPointcut"/> 13 <aop:after-throwing method="afterThrowing" throwing="ex" pointcut-ref="myPointcut"/> 14 <aop:around method="around" pointcut-ref="myPointcut"/> 15 </aop:aspect> 16 </aop:config>
在spring3以上版本中使用spring的依赖注入(注解或者xml方式)和aop功能时,发现了一个问题,如果不设 置<aop:aspectj-autoproxy proxy-target-class="true"/>那么在获取bean时一直报:(无论通过name还是type都获取不到bean)
org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type
或者
java.lang.ClassCastException: com.sun.proxy.$Proxy12 cannot be cast to cn.edu.nuc.SpringTest.service.impl.DemoServiceImpl
proxy-target-class="true" 与proxy-target-class="false"的区别:
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class
属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个
属性被省略,那么标准的JDK 基于接口的代理
xml的引用( 注解)
<!-- 注解 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
增强处理类
1 @Aspect 2 public class ServiceLogging { 3 4 private Logger log = Logger.getLogger(getClass()); 5 6 //前置增强处理 aspect method 7 @Before("execution(public * com.pb.bdqn.service.*.*(..))") 8 public void before(JoinPoint jp){ 9 log.info("前置处理"+jp.getTarget().getClass().getSimpleName()); 10 log.info("连接点方法"+jp.getSignature()); 11 log.info("连接点方法参数"+jp.getArgs()[0]); 12 13 } 14 }
1 /** 2 * 增强处理类 3 * @author Administrator 4 * 5 */ 6 @Aspect 7 public class ServiceLogging { 8 9 private Logger log = Logger.getLogger(getClass()); 10 //切入点 11 @Pointcut("execution(public * com.bdqn.service.*.*(..))") 12 public void myPointcut(){} 13 14 @Before("myPointcut()") 15 //前置增强处理 aspect method 16 // @Before("execution(public * com.pb.bdqn.service.*.*(..))") 17 public void before(JoinPoint jp){ 18 log.info("前置处理"+jp.getTarget().getClass().getSimpleName()); 19 log.info("连接点方法"+jp.getSignature()); 20 log.info("连接点方法参数"+jp.getArgs()[0]); 21 22 } 23 @After("myPointcut()") 24 public void after(){ 25 log.info("后置处理"); 26 } 27 @AfterReturning(pointcut="myPointcut()",returning="rt") 28 public void afterReturning(Object rt){ 29 log.info("afterReturning后置处理"+rt); 30 } 31 @AfterThrowing(pointcut="myPointcut()",throwing="ex") 32 public void afterThrowing(Exception ex){ 33 log.info("afterThrowing处理"+ex.getMessage()); 34 }
1 Ioc中xml注解<context:component-scan base-package="com.bdqn.*"></context:component-scan> 2 AOP中xml注解<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
around的执行步骤和其他都不一样
1 @Around("myPointcut()") 2 public Object around(ProceedingJoinPoint pjp) throws Throwable{ 3 log.info("around方法前执行"); 4 Object obj = pjp.proceed(); 5 log.info("around方法后执行"); 6 return obj; 7 }
原文:http://www.cnblogs.com/xuerong/p/4922518.html