5-Spring-AOP-基于注解

4 篇文章 0 订阅

Spring-AOP-基于注解


一. 介绍

AOP 是面向切面编程,是一种思想,以一种横向抽取的机制,取代了传统的纵向继承的重复性代码编写方式(性能监控、事务管理、安全检查、缓存、日志)

1.1 准备工作

开启注解功能

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd"
>
    <!--开启Spring的注解功能-->
    <context:annotation-config/>
    <!-- 扫描包 -->
    <context:component-scan base-package="org.buaa.service"/>

    <!-- 开启AOP注解 -->
    <aop:aspectj-autoproxy/>
...

1.2 编写增强类

记得增强类也要交给Spring管理,需要加上注解@Component

@Component
public class CarAdvice{
    // 最终通知
    public void after(){
        System.out.println("最终");
    }
    // 前置
    public void before(){
        System.out.println("前置");
    }
    // 后置
    public void afterReturning(){
        System.out.println("后置");
    }
}

1.3 配置切入点

在方法上编写切入点的表达式

@Component
@Aspect // 这个一定要加
public class CarAdvice{
    // 最终通知
    @After(value = "execution(* org.buaa.service..*.*(..))")// 也可以不写value,直接写表达式
    public void after(){
        System.out.println("最终");
    }
    // 前置
    @Before("execution(* org.buaa.service.*.*Delete(..))")
    public void before(){
        System.out.println("前置");
    }
    // 后置
    @AfterReturning("execution(* org.buaa.service..*.*(..))")
    public void afterReturning(){
        System.out.println("后置");
    }
}

1.4 测试结果


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class Test{
    @Autowired
    private CarService carService;
    @Test
    public void demo(){
        carService.addCar();
    }
    /*
    环绕,之前执行
    前置
    环绕,之后执行
    最终执行
    */

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值