Spring的aop两种配置实现方法

Spring的AOP实现

实现方式一:配置文件实现(xml)

配置文件:
ioc配置需要装配的对象(包括切面类):

<bean id="userService" class="com.sgl.service.UserServiceImpl"></bean>
<bean id="pointCut" class="com.sgl.diy.PointCut"></bean>

配置文件实现aop:

<aop:config>
        <aop:aspect id="userService" ref="pointCut">
            <aop:before method="before" pointcut="execution(* com.sgl.service.*.*(..))"></aop:before>
            <aop:after method="after" pointcut="execution(* com.sgl.service.*.*(..))"></aop:after>
        </aop:aspect>
</aop:config>

简单切面类:

public class PointCut{
    public void before(){
        System.out.println("方法执行前");
    }
    public void after(){
        System.out.println("方法执行后");
    }
}

业务类实现:

public class UserServiceImpl implements UserService{
    public void add(){
        System.out.println("执行了add方法");
    }

}

测试:

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
UserService userService = (UserService) ac.getBean("userService");
userService.add();

测试结果:
在这里插入图片描述

实现方式二:注解实现

配置文件:
ioc配置需要装配的对象(包括切面类):

<bean id="userService" class="com.sgl.service.UserServiceImpl"></bean>
<bean id="pointCut" class="com.sgl.diy.PointCut"></bean>

配置注解:

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<context:component-scan base-package="com.sgl.*"></context:component-scan>

业务类实现与上相同

切面类使用环绕通知:

@Around("execution(* com.sgl.service.*.*(..))")
    public void around(ProceedingJoinPoint pjp){
        System.out.println("环绕方法执行前");

        try {
            pjp.proceed();
            int i=9/0;
        } catch (Throwable throwable) {
            System.out.println("抛异常");
        }
        System.out.println("环绕方法执行后");
    }

测试结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值