1、AOP的概念
AOP:面向切面的编程,在不改变原来代码的基础之上,对原有的功能进行增强。 底层的设计模式:就是代理设计模式。
2、使用Spring 实现AOP(ASPECTJ)
方式一:注解
(1)在resource里面,创建spring的xml文件,主要是完成二件事。
(1)对类开启注解扫描
(2)开启aspectj的自动代理
<?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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="com.fan.aop"/>
<!--开启AspectJ生产代理对象-->
<aop:aspectj-autoproxy/>
</beans>
创建业务类,通过注解创建对象,需要用@Component
package com.fan.aop;
import org.springframework.stereotype.Component;
@Component
public class User {
public void add(){
System.out.println("add...");
}
}
创建增强类,通过注解创建类,在类上面加入@Aspect,并在增强的方法上加上(
@Before:前置通知 @After:最终通知,遇到异常也会执行 @AfterReturning:后置通知,遇到异常不会执行 @AfterThrowing:异常通知 @Around:环绕通知,是再被增强的业务代码的前后 )
如果遇到多个类,对一个业务代码进行增强的时候,需要给不同的增强类进行优先级配置,即就是引入@Order,括号里面写数字,数字越小优先级越高。
package com.fan.aop;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Component
@Aspect
public class UserProxy {
//前置通知
@Before(value = "execution(* com.fan.aop.User.add(..))")
public void before(){
System.out.println("Before...");
}
}
方式二:xml配置,类的代码跟上面一样,唯一的区别是将注解去掉了。
<?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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--创建实体类-->
<bean id="user" class="com.fan.aop.User"/>
<bean id="userProxy" class="com.fan.aop.UserProxy"/>
<!--Aop的配置-->
<aop:config>
<!--配置切入点-->
<aop:pointcut id="p" expression="execution(* com.fan.aop.User.add(..))"/>
<!--配置切面-->
<aop:aspect ref="userProxy">
<!--增强作用在具体的方法上-->
<aop:before method="before" pointcut-ref="p"/>
</aop:aspect>
</aop:config>
</beans>