Spring的AOP的开发的AspectJ配置

bean.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 目标对象 -->
    <bean id="tableServiceImpl" class="com.baidu.impl.TableServiceImpl"></bean>
    <!-- 
     AspectJ增强:
        @Before 前置通知,相当于BeforeAdvice
        @AfterReturning 后置通知,相当于AfterReturningAdvice
        @Around 环绕通知,相当于MethodInterceptor
        @AfterThrowing抛出通知,相当于ThrowAdvice
        @After 最终final通知,不管是否异常,该通知都会执行
        @DeclareParents 引介通知,相当于IntroductionInterceptor
     -->
    <bean id="myAspect" class="com.baidu.service.MyAspect"></bean>
    <aop:config>
        <aop:aspect ref="myAspect">
            <aop:pointcut expression="execution(* com.baidu.impl..add*(..))" id="point1"/>
            <aop:before method="myBefore" pointcut-ref="point1"/>
             <aop:after-returning method="myAfterReturning" pointcut-ref="point1" returning="result"/>
            <aop:around method="myAround" pointcut-ref="point1" /> 
            <aop:after-throwing method="myAfterThrowing" pointcut-ref="point1" throwing="ex"/>
        </aop:aspect>
    </aop:config>
</beans>

编写被代理对象

public interface TableServiceI {    
    void delete();
    String add();
}
public class TableServiceImpl implements TableServiceI{

    @Override
    public void delete() {
        System.out.println("delete");
    }
    @Override
    public String add() {
        System.out.println("add");
        return "add";
    }
}

编写增强的代码

public class MyAspect {

    public void myBefore(JoinPoint joinPoint) {
        System.out.println("前置增强"+joinPoint.toString());
    }
    public void myAfterReturning(JoinPoint joinPoint,Object result) {
        System.out.println("后置增强,返回值"+result);
    }
    public void myAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知1");
        Object proceed = joinPoint.proceed();
        System.out.println("环绕通知2,返回值"+joinPoint);
    }
    public void myAfterThrowing(JoinPoint joinPoint,Exception ex){
        System.out.println("异常了,,,"+ex.getMessage());
    }
}

猜你喜欢

转载自blog.csdn.net/chenbingbing111/article/details/81037862