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();
}
/*
环绕,之前执行
前置
环绕,之后执行
最终执行
*/
}