(二)Spring AOP:基于注解

来源:互联网 发布:华能营口电厂知乎 编辑:程序博客网 时间:2024/05/01 22:26

步骤一、二、五同上文。主要区别就在于步骤三、四,那么直接到步骤三吧。。。

三、切面类

package cn.cjc.spring.aop.aspect;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.Before;import org.aspectj.lang.annotation.Pointcut;@Aspectpublic class LogAnnotationAspect {    /**     * 切点1     */    @Pointcut("execution(* cn.cjc.spring.aop.service..*.*(String)) && args(aopArgs)")    public void pointcut1(String aopArgs) {    }    /**     * 切点2     */    @Pointcut("execution(* cn.cjc.spring.aop.service..*.*(..))")    public void pointcut2() {    }    /**     * 前置通知     */    @Before("pointcut2()")    public void before(JoinPoint call) {        String className = call.getTarget().getClass().getName();        String methodName = call.getSignature().getName();        System.out.println("前置通知:" + className + "类的" + methodName + "方法开始执行");    }    /**     * 后置通知     */    @AfterReturning("pointcut2()")    public void afterReturn() {        System.out.println("后置通知");    }    /**     * 最终通知     */    @After("pointcut1(userName)")    public void after(String userName) {        System.out.println(userName + ",最终通知");    }    /**     * 异常通知     */    @AfterThrowing("pointcut2()")    public void afterThrow() {        System.out.println("异常通知");    }    /**     * 环绕通知     */    @Around("pointcut1(userName)")    public Object around(ProceedingJoinPoint call, String userName) {        System.out.println("环绕通知");        this.before(call);        Object result = null;        try {            result = call.proceed();            this.afterReturn();        } catch (Throwable e) {            this.afterThrow();        } finally {            this.after(userName);        }        return result;    }}
发现比上文中的切面类多了@Aspect、@Pointcut、@Before等注解,这些注解的作用就是把类声明为切面,把普通方法声明为切点或通知

四、spring配置文件beans.xml

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:aop="http://www.springframework.org/schema/aop"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd                    http://www.springframework.org/schema/aop                    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">    <!--普通的bean声明-->    <bean id="logService" class="cn.cjc.spring.aop.service.LogService"/>    <bean id="logAnnotationAspect" class="cn.cjc.spring.aop.aspect.LogAnnotationAspect"/>    <!--aop配置开始,表示支持AspectJ注解的切面类-->    <aop:aspectj-autoproxy/></beans>
测试方法和上文一样,不再赘述。


0 0
原创粉丝点击