前言
Spring中的AOP是基于动态代理实现的,首先理解代理模式,更有利于后面AOP的理解。
一、代理模式
1.静态代理
角色分析:
- 抽象角色∶一般会使用接口或者抽象类来解决
- 真实角色∶被代理的角色
- 代理角色︰代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人
- 接口:Rent.java
public interface Rent {
//租房
void rent();
}
- 真实角色:房东
//房东
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东出租!");
}
}
- 代理角色:中介
//代理:中介
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
//收取中介费,租房
cost();
host.rent();
}
//中介费
public void cost(){
System.out.println("收中介费!");
}
}
- 客户:
public class Client {
public static void main(String[] args) {
//房东要租房
Host host = new Host();
//代理:中介帮助房东租房子,并收取中介费
Proxy proxy = new Proxy(host);
//租房给你
proxy.rent();
}
}
代理模式的好处:
- 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务
- 公共也就交给代理角色,实现了业务的分工
- 公共业务发生扩展的时候,方便集中管理
缺点: - 一个真实角色就会产生一个代理角色,代码量会翻倍,开发效率会变低
2.动态代理(JDK动态代理)
- 动态代理的角色和静态代理的一样
- 动态代理的代理类是动态生成的,静态代理的代理类是我们提前写好的
- 核心是InvocationHandler和Proxy
- 一个动态代理类代理的是一个接口,一般就是对应的一类业务
- 一个动态代理类可以代理多个类,只要是实现了同一个接口即可
- 接口:抽象角色
public interface Rent {
//租房
void rent();
}
- 真实对象:
//房东
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东出租!");
}
}
- 生成动态代理类:
//等我们会用这个类,自动生成代理类
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果:
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//附加属性
cost();
Object result = method.invoke(target,args);
return result;
}
public void cost(){
System.out.println("收中介费!");
}
}
二、Spring AOP实现
-
面向切面编程(AOP)和面向对象编程(OOP)类似,也是一种编程模式。
-
Spring AOP 是基于 AOP 编程模式的一个框架,它的使用有效减少了系统间的重复代码,达到了模块间的松耦合目的。
-
AOP 的全称是“Aspect Oriented Programming”,即面向切面编程,它将业务逻辑的各个部分进行隔离,使开发人员在编写业务逻辑时可以专心于核心业务,从而提高了开发效率。
-
AOP 采取横向抽取机制,取代了传统纵向继承体系的重复性代码,其应用主要体现在事务处理、日志管理、权限控制、异常处理等方面。
-
AOP的一些基本概念:
-
横切关注点: 跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
-
切面(ASPECT):横切关注点被模块化的特殊对象。即,它是一个类。
-
通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
-
目标(Target):被通知对象。
-
代理(Proxy):向目标对象应用通知之后创建的对象。
-
切入点(PointCut):切面通知执行的“地点"的定义。
-
连接点(JointPoint):与切入点匹配的执行点。
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
通知类型 | 连接点 | 实现接口 |
---|---|---|
前置通知 | 使用方法前 | org.springframework.aop.MethodBeforeAdvice |
后置通知 | 方法后 | org.springframework.aop.AfterReturningAdvice |
环绕通知 | 方法前后 | org.aopalliance.intercept.MethodInterceptor |
异常抛出通知 | 方法抛出异常 | org.springframework.aop.ThrowsAdvice |
引介通知 | 类中增加新的方法属性 | org.springframework.aop.IntroductionInterceptor |
在AOP不改变原来代码的情况下,增加新的功能。
- 使用AOP需要导入jar包依赖:
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
1.基于接口实现
- 接口UserService:
package com.gaolang.service;
public interface UserService {
void add();
void delete();
void update();
void select();
}
- 接口实现类:UserServiceImpl
package com.gaolang.service;
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("更新了一个用户");
}
@Override
public void select() {
System.out.println("查询了一个用户");
}
}
- 5种类型的Advice:
前置日志:在接口方法调用前调用
package com.gaolang.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
//使用接口方法前调用:这里实现一个前置日志
public class BeforeLog implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//objects:参数
//o:目标对象
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"的"+method.getName()+"被执行了");
}
}
后置日志:在接口方法调用后调用
package com.gaolang.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
//method:要执行的目标对象的方法
//objects:参数
//o1:目标对象
//o:返回值
@Override
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回结果:"+o);
}
}
- applicationContext.xml
需要导入依赖:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.gaolang.service.UserServiceImpl"/>
<bean id="beforeLog" class="com.gaolang.log.BeforeLog"/>
<bean id="afterLog" class="com.gaolang.log.AfterLog"/>
<aop:config>
<!--切入点 execution(要执行的位置)是一个 表达式,格式固定-->
<aop:pointcut id="pointcut" expression="execution(* com.gaolang.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加-->
<aop:advisor advice-ref="beforeLog" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
</aop:config>
</beans>
- 测试类:
import com.gaolang.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
运行结果:
com.gaolang.service.UserServiceImpl的add被执行了
增加了一个用户
执行了add方法,返回结果:null
与动态代理对比理解:客户和测试类对应
2.自定义类实现
- 自定义类:
package com.gaolang.diy;
public class DiyPointCut {
//使用方法前
public void before(){
System.out.println("====使用方法前====");
}
//使用方法后
public void after(){
System.out.println("====使用方法后====");
}
}
- applicationContext.xml
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.gaolang.service.UserServiceImpl"/>
<!--方式二:自定义类-->
<bean id="diy" class="com.gaolang.diy.DiyPointCut"/>
<aop:config>
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="pointcut" expression="execution(* com.gaolang.service.UserServiceImpl.*(..))"/>
<!--通知-->
<aop:before method="before" pointcut-ref="pointcut"/>
<aop:after method="after" pointcut-ref="pointcut"/>
</aop:aspect>
</aop:config>
</beans>
- 测试类:
import com.gaolang.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
运行结果:
====使用方法前====
增加了一个用户
====使用方法后====
3.注解实现
- 切面类
package com.gaolang.annotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //标注这个类是个切面
public class AnnotationPointCut {
//使用方法前
@Before("execution(* com.gaolang.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("====使用方法前====");
}
//使用方法后
@After("execution(* com.gaolang.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("====使用方法后====");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.gaolang.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕前");
Signature signature = joinPoint.getSignature();//获得签名
System.out.println("signature:"+signature);
Object proceed = joinPoint.proceed();//执行方法
System.out.println("环绕后");
}
}
- applicationContext.xml 开启注解:
<aop:aspectj-autoproxy/>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.gaolang.service.UserServiceImpl"/>
<!--方式三:注解-->
<bean id="annotationPointCut" class="com.gaolang.annotation.AnnotationPointCut"/>
<!--开启注解支持! JDK(默认proxy-target-class="false") cglib(proxy-target-class="true")-->
<aop:aspectj-autoproxy/>
</beans>
- 测试类:
import com.gaolang.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.add();
}
}
运行结果:
环绕前
signature:void com.gaolang.service.UserService.add()
====使用方法前====
增加了一个用户
====使用方法后====
环绕后