SpringAOP的三种方式

本文详细介绍了如何在Spring框架中使用AOP(面向切面编程)来增强代码的功能,包括通过Java API、AspectJ和XML aop标签三种方式实现方法前、后通知和点切面的配置。

1.作用对象

public class Person {
    private Integer id;
    private String name;
	// getter setter省略
    public void findPerson() {
        Person person = new Person(1, "JDK");
        System.out.println("findperson 被执行");
    }
}
<bean id="person" class="beans.Person">
    <property name="id" value="2"></property>
    <property name="name" value="Python"></property>
</bean>

2.方法一:Java API

public class MyAdvice implements MethodBeforeAdvice, AfterReturningAdvice {

    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("准备执行方法: " + method.getName());
    }

    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println(method.getName() + " 方法执行结束");
    }
}
<!-- 定义advisor -->
<bean id="myAdvice" class="aop.MyAdvice"></bean>

<!-- 配置规则, 拦截方法名为 find* -->
<bean class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
	<property name="advice" ref="myAdvice"></property>
    <property name="pattern" value="beans.*.find.*"></property>
</bean>

<!-- 定义DefaultAdvisorAutoProxyCreator 使所有的 advisor配置自动生效 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"></bean>

3.方法二:AspectJ

@Aspect
public class MyAspectJ {

    // 配置拦截类 Person
    @Pointcut("execution(* beans.Person.*(..))")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void doBefore() {
        System.out.println("执行doBefore方法");
    }

    @After("pointCut()")
    public void doAfter() {
        System.out.println("执行doAfter方法");
    }
}
<!-- 开启@AspectJ的注解 -->
<aop:aspectj-autoproxy/>

<bean class="aop.MyAspectJ"></bean>

4.方法三:XML aop标签

public class MyPointcut {

    public void doBefore() {
        System.out.println("执行  doBefore方法");
    }

    public void doAfter() {
        System.out.println("执行  doAfter 方法");
    }
}

<!-- 拦截处理类 -->
<bean id="myPointcut" class="aop.MyPointcut"></bean>
<aop:config>
    <!-- 拦截规则配置 -->
    <aop:pointcut id="pointcutConfig" expression="execution(* beans.Person.*(..))"></aop:pointcut>
    <!-- 拦截方法配置 -->
    <aop:aspect ref="myPointcut">
        <aop:before method="doBefore" pointcut-ref="pointcutConfig"></aop:before>
        <aop:after method="doAfter" pointcut-ref="pointcutConfig"></aop:after>
    </aop:aspect>
</aop:config>

5.测试

ApplicationContext context =
               new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Person person = context.getBean("person", Person.class);
person.findPerson();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值