AOP学习——配置Spring AOP【2】,使用annotation

本文介绍如何使用Java注解(Annotation)配置面向切面编程(AOP),避免在Spring的XML配置文件中编写复杂的AOP配置。通过示例展示了如何定义切面类、切入点表达式及增强方法。

使用 annotation 配置 AOP

使用 Java1.5 或以上版本,我们可以使用 annotation 设置 AOP 。这样我们不再需要往 beans.xml 里面编写 aop:config 之类的配置代码。

需要在 beans.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-2.5.xsd

http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

    <!-- 使 bean 可以使用 annotation -->

    <aop:aspectj-autoproxy />   

  

   <!--

    <aop:config>

        <aop:aspect id="aspectDemo" ref="aspectBean">

            <aop:pointcut id="somePointcut"

            expression="execution(* annoaop.Component.business*(..))" />

            <aop:before pointcut-ref="somePointcut"

             method="validateUser" />

            <aop:before pointcut-ref="somePointcut"

            method="beginTransaction" />

            <aop:after-returning pointcut-ref="somePointcut"

            method="endTransaction" />

            <aop:after-returning pointcut-ref="somePointcut"

            method="writeLogInfo" />

        </aop:aspect>

    </aop:config>

    -->

    <bean id="aspectBean"

    class="annoaop.AspectBean">

    </bean>  

   

    <bean id="component"

    class="annoaop.ComponentImpl">

    </bean>

</beans>

      

       之后我们就往我们的切面类 AspectBean 添加 annotation

@Aspect

public class AspectBean {

    // 定义切入点,切入点表达式为 Component 接口的以 business 开头的所有方法,参数使用 .. 表示所有参数

    @Pointcut("execution(* annoaop.Component.business*(..))")

    public void somePointcut(){

    }

   

    @Around("somePointcut()")

    public void processBusiness(ProceedingJoinPoint joinPoint) throws Throwable{

        System.out.println(" 执行用户验证 !");

        System.out.println(" 开始事务 ");

        joinPoint.proceed();

        System.out.println(" 结束事务 ");

         System.out.println(" 书写日志信息 ");

    }

}

注意红色部分:

首先使用 @Aspect 给这个类声明为一个切面。

之后使用 @Pointcuttarget 声明一个切入点。

然后使用 @Around 声明环绕增强 processBusiness 。参数只有一个,就是 ProceedingJoinPoint ,这个参数就代表 somePointcut 这个方法,调用 proceed() 方法则执行切入点方法。在这个环绕增强里面,我们可以轻松地按照自己的思路配置切入点执行前或者执行后需要增加的操作。

运行主方法:

执行用户验证 !

开始事务

bussiness

结束事务

书写日志信息
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值