Spring的第四天AOP之注解版

Spring的第四天AOP之注解版

在上一篇博客中,介绍了Spring的AOP的xml版本的使用,在这篇博客中,我将介绍一下,注解版的使用。

常用注解

注解 通知
@After 通知方法会在目标方法返回或抛出异常后调用
@AfterRetruening 通常方法会在目标方法返回后调用
@AfterThrowing 通知方法会在目标方法抛出异常后调用
@Around 通知方法将目标方法封装起来
@Before 通知方法会在目标方法执行之前执行

xml文件配置

<!-- 声明激活自动扫描组件功能,spring会去自动扫描com.weno下面或则自包下面的java文件,如果扫描到了@Component,@Controller等这些注解的类,就会把他们注册为bean,名字为类名但是首字母小写 -->
<context:component-scan base-package="com.weno.*"/>

<!-- Spring默认不支持使用@AspectJ的切面声明
    使用如下配置可以使Spring发现那些配置@AspectJ的bean,并且创建代理,织入切面 -->
<aop:aspectj-autoproxy/>

通知类

//声明这是一个组件,使其能够被扫描到
@Component
//声明这是一个切面Bean
@Aspect
public class Advices {

    //减少重复性工作
    @Pointcut(value = "execution(* com.weno.pojo.User.msg())")
    public void msg(){
    }

    @Before(value = "msg()")
    public void beforeMethod(){
        System.out.println("我正在切前置");
    }


    @AfterReturning(returning = "rvt",value = "msg()")
    public void returnMethod(String rvt){
        System.out.println("我正在切返回值"+rvt);
    }

    @After( value = "msg()")
    public void afterMethod(){
        System.out.println("我正在切后置");
    }

    @AfterThrowing(value = "execution(* com.weno.pojo.User.msg2())")
    public void errorMethod(){
        System.out.println("我正在切错误");
    }

}

被切的类

import org.springframework.stereotype.Component;

@Component
public class User {

    public String msg(){
        System.out.println("我叫msg");

        return "你是谁?";
    }
    public void msg2(){
        System.out.println("被错误通知切");
        throw new RuntimeException("我故意的错");
    }
}

啊啊啊啊!恭喜IG




猜你喜欢

转载自www.cnblogs.com/xiaohuiduan/p/9901739.html
今日推荐