Spring中基于配置XML与Annotation注解配置AOP

来源:互联网 发布:手机没有usb共享网络 编辑:程序博客网 时间:2024/05/17 01:38
Spring中基于配置XML与Annotation注解配置AOP

基于AspectJ注解的AOP实现

 

@AspectJ@Pointcut@Before@AfterReturning@AfterThrowing@Around

定义bean-productInfoService类

 

@Component("ProductInfoService")public class ProductInfoServiceImpl implements ProductInfoService

</bean><!--配置业务类的Bean--><bean id = "productInfoService" class = "com.shw.service.impl.ProductInfoServiceImpl">
</bean>



定义日志切面bean

@Component //定义日志切面beanpublic class AllLogAdivce

<!--配置日志通知类(切面)的Bean>
<bean id = "allLogAdvice" class = "com.shw.aop.AlllogAdvice">
</bean>


定义切面

 

@Aspect //定义切面
@Component //定义日志切面Bean
public class AlllogAdvice

<!-- 配置AOP,让日志通知到业务方法--><aop:config><!--配置日志的切面--><aop:aspect id = "logaop" ref="allLogAdcvice">


定义切入点  Pointcut(“execution(*com.shw.service.ProductInfoService.*(..))”)表示拦截

此包中类下的所有方法

定义切入点名称类allMethod()后面通知时引用  方法内无内容

@Pointcut("execution(*com.shw.service.ProductInfoService.*(..))")private void allMethod(){}



在xml文件中切入点的ID是logpointcut
<!--定义切入点><aop:pointcut expression= "execution"(*com.shw.service.ProductInfoService.*(..) id = "logpointcut")

声明4种通知

@Before("allMethod()")public void myBeforeAdvice(JoinPoint joinPoint){}

 
<!--将日志通知类中的”myBeforAdvice”方法作为前置通知--><aop:before method = "myBeforeAdvice" pointcut -ref = "logpointcut">

 

返回通知

@AferReturning("allMethod()")public void myAfterReturnAdvice(JoinPoint joinpoint){}


异常通知

AfterThrowing(“alltMethod()”)public void myThrowingAdvice(Jopint jopint,Excepet e){}


环绕通知

 

 

接下来配置命名空间,加入aop bean context3个命名空间

 


再配置自动扫描的com.shw包下的

Context:component-scanbase-package=“com.shw”


配置开启基于@AspectJ切面的注解处理器

<aop:aspect-autoproxy>




原创粉丝点击