SpringAop之接口方法增加通知

9 篇文章 0 订阅

代理三要素:

1)被代理的目标

2)代理的增强类

3)增强类和目标的关联

SpringAOP需要引入的maven坐标

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aspects</artifactId>

</dependency>

一:给接口方法增加的通知切面类(增强类)

/ 在一个切面类,可以提供多个 advice方法
public class MyAspectJ {

    // 环绕通知: 返回object
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object returnVal = null;
        try {
           // 1 开启事务
           System.out.println("================1 开启事务");
           // 2 执行一组sql语句
           returnVal = joinPoint.proceed();
           // 3.1  提交事务
           System.out.println("================2 提交事务");
       } catch (Exception ex) {
           ex.printStackTrace();
           // 3.2 回滚事务
            System.out.println("================3 回滚事务");
       } finally {
           // 4 释放资源
            System.out.println("================4 释放资源");
       }
       return returnVal;
    }

    // 前置通知
    public void before01(JoinPoint joinPoint) {
        System.out.println("--------------------- 前置通知: 开启事务 ... ..." );
    }
}

二:需要增加通知的接口(目标类)

public interface UserService {

    public User findUserById(Long id);

    public List<User> findUserAll();

    public int deleteUserById(String id);

    public int updateUser(User user);

    public int addUser(User user);
}

三:spring配置文件增加aop配置使切面类与接口类绑定关系

<!--1 配置切面增强类-->
<bean id="myAspectJ" class="com.xucj.aspect.MyAspectJ"/>
<!--2 配置切入点和切面-->
<aop:config proxy-target-class="false">
   <!--2.1 ref引入通知方法所在的类-->
   <aop:aspect ref="myAspectJ">
      <!--2.2 配置六种通知类型和切入点-->
      <aop:pointcut id="myPointcut" expression="bean(*ServiceImpl)"/>
<!--  around:环绕通知,method:切面增强类增强的方法-->
<aop:around method="around" pointcut-ref="myPointcut"/>
<!--后置通知
<aop:after-returning method="afterRegurning" pointcut-ref="myPointcut" returning="returnObject"/>-->
<!--异常通知
<aop:after-throwing method="afterThrowing" pointcut-ref="myPointcut" throwing="ex"/>-->
<!--最终通知
<aop:after method="after" pointcut-ref="myPointcut" />-->
<!--前置通知
      <aop:before method="before01" pointcut-ref="myPointcut"/>-->
   </aop:aspect>
</aop:config>

四:测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringTest {

    @Autowired
    private UserService userService;

    @Test
    public void demo01() {
        userService.findUserById(1L);
    }
}

运行结果:

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值