在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期间动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。主要用于日志记录,性能统计,安全控制,事务处理,异常处理等等。
步骤
- 创建目标接口和目标类
public interface TargetInterface {
void save();
void run(int i);
}
@Component("target")
public class Target implements TargetInterface {
@Override
public void save() {
System.out.println("save running ...");
}
@Override
public void run(int i) {
i = 1/0;
System.out.println("running ...");
}
}
- 创建切面类
@Component("myAspect")
@Aspect //标注当前类是切面
public class MyAspet {
@Before("execution(* com.littlepants.anno.*.*(..))")
public void before(){
System.out.println("前置增强....");
}
public void after(){
System.out.println("后置增强...");
}
public Object around(ProceedingJoinPoint point) throws Throwable {
System.out.println("before");
Object proceed = point.proceed();//切点方法
System.out.println("after");
return proceed;
}
public void afterThrowing(){
System.out.println("异常抛出");
}
}
- 将目标类和切面类的对象创建权交给Spring
@Component("target")
- 在切面类中使用注解配置织入关系
@Aspect
- 在配置文件中开启组件扫描和AOP自动代理
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.littlepants.anno"></context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
注解通知的类型
名称 | 注解 | 备注 |
---|---|---|
前置 | @Before | 方法在切入点方法之前执行 |
后置 | @AfterReturning | 方法在切入点方法之后执行 |
环绕 | @Around | 方法在切入点方法之前和之后均执行 |
异常抛出 | @AfterThrowing | 方法在异常抛出后执行 |
最终 | @After | 类似于finally,无论是否有异常均执行 |