spring学习----aop配置demo

本文介绍了一种使用Spring AOP进行切面编程的方法。通过定义通知类实现Advice接口,结合配置文件设置切入点和切面,实现了对业务方法的前置和后置通知。测试结果表明该方法有效。

注意

  aop:aspect   切面类是普通类即可
  aop:advisor  切面类必须实现  advice接口   如:MethodBeforeAdvice    AfterReturningAdvice等

定义通知(实现Advice)

public class MyAfterAdvice implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
        System.out.println("=========我是afterReturn通知方法=============");
    }
}
public class MyBeforeAdvice implements MethodBeforeAdvice{
    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        System.out.println("=========我是前置通知方法=============");
    }
}

普通通知(不实现Advice)

public class MyNoAdvice {
    public void before() throws Throwable {
        System.out.println("=============我的普通的before前置方法====================");
    }


    public void after() throws Throwable {
        System.out.println("=============我的普通的After后置方法====================");
    }
}

业务类

public interface IBussinessService {
    void bussiness();

    void sayHello();
}
public class BussinessServiceImpl implements IBussinessService{
    @Override
    public void bussiness() {
        System.out.println("=========我是业务方法==========");
    }

    @Override
    public void sayHello() {
        System.out.println("=========我是say Hello==========");
    }
}

测试类

@Test
    public void test1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:beans.xml");
        IBussinessService bussinessService =  applicationContext.getBean("bussinessService",IBussinessService.class);
        bussinessService.bussiness();
    }

配置文件

<!-- ==========================测试AOP============================= -->
    <bean id="myBeforeAdvice" class="com.chenfei.advice.MyBeforeAdvice"></bean>
    <bean id="myAfterAdvice" class="com.chenfei.advice.MyAfterAdvice"></bean>
    <bean id="myNoAdvice" class="com.chenfei.advice.MyNoAdvice"/>
    <bean id="bussinessService" class="com.chenfei.service.impl.BussinessServiceImpl"></bean>

    <aop:config>
        <aop:pointcut id="pointtest1" expression="execution(* com.chenfei.service.impl.*.*(..))" />
        <aop:aspect ref="myNoAdvice">
            <aop:before method="before" pointcut-ref="pointtest1"/>
            <aop:after method="after" pointcut-ref="pointtest1"/>
        </aop:aspect>
    </aop:config>
    <aop:config>
        <aop:pointcut id="pointtest2" expression="execution(* com.chenfei.service.impl.*.*(..))" />
        <aop:advisor pointcut-ref="pointtest2" advice-ref="myBeforeAdvice" />
        <aop:advisor pointcut-ref="pointtest2" advice-ref="myAfterAdvice" />
    </aop:config>

测试结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值