Spring-AOP
Spring
代理模式
为什么学习代理模式?
因为这就是SpringAOP的底层原理【SpringAOP和SpringMVC】
代理模式分为两种:
- 静态代理
- 动态代理

静态代理
角色分析:
- 抽象角色:一般会使用接口或者抽象类来解决
- 真实角色:被代理的角色
- 代理角色:代理真实角色,代理真实角色后,我们一般会做一些附属操作
- 客户:访问代理对象的人
代码示例:
1.接口
package com.test.demo01;
public interface Rent {
void Rent();
}
2.真实角色
package com.test.demo01;
public class Host implements Rent{
public void Rent() {
System.out.println("Host要出租房子");
}
}
package com.test.demo01;
public class Client implements Rent{
public void Rent() {
System.out.println("Client要租房子");
}
}
3.代理角色
package com.test.demo01;
public class Proxy implements Rent{
private Host host;
//构造方法,注入值
public Proxy(Host host){
this.host=host;
}
public void Rent() {
seeHouse();
host.Rent();
fare();
sighacontract();
}
//看房
public void seeHouse(){
System.out.println("Proxy带领看房");
}
//收费
public void fare(){
System.out.println("Proxy收中介费");
}
//签合同
public void sighacontract(){
System.out.println("Proxy签合同");
}
}
4.客户端方访问代理角色
import com.test.demo01.Host;
import com.test.demo01.Proxy;
public class MyTest {
public static void main(String[] args) {
//房东要出租房子
Host host = new Host();
//直接找房东租房子
//host.Rent();
//找代理租房子,不直接接触房东
Proxy proxy = new Proxy(host);
proxy.Rent();
//代理租房子,会有许多的附加属性
proxy.Rent();
}
}
示例二:(在源代码的基础上添加日志信息的功能)
```java
package com.test.service;
public interface UserService {
void add();
void delete();
void update();
void select();
}
package com.test.service;
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("添加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("更新了一个用户");
}
public void select() {
System.out.println("查询了用户");
}
}
package com.test.service;
//添加代理,增加Log业务功能
public class UserServiceProxy implements UserService{
private UserServiceImpl userServiceimpl;
public UserServiceImpl getUserServiceimpl() {
return userServiceimpl;
}
//使用set方式进行对象注入,便于灵活调用
public void setUserServiceimpl(UserServiceImpl userServiceimpl) {
this.userServiceimpl = userServiceimpl;
}
public void add() {
log("add");
userServiceimpl.add();
}
public void delete() {
log("delete");
userServiceimpl.delete();
}
public void update() {
log("update");
userServiceimpl.update();
}
public void select() {
log("select");
userServiceimpl.select();
}
//添加日志信息
public void log(String msg){
System.out.println("[log]:"+msg+"方法执行了");
}
}
import com.test.service.UserServiceImpl;
import com.test.service.UserServiceProxy;
public class MyTest2 {
public static void main(String[] args) {
UserServiceImpl userserviceimpl = new UserServiceImpl();
UserServiceProxy userserviceproxy = new UserServiceProxy();
userserviceproxy.setUserServiceimpl(userserviceimpl);
userserviceproxy.add();
}
}
代理模式的优点:
- 可以使真实角色的操作更加纯粹!不用去关注一些公共业务
- 公共的就交给代理角色!实现了业务的分工!
- 公共业务的发展的时候,方便集中管理。
缺点: - 一个真实角色的就会产生一个代理角色,代码量会翻倍,开发效率会降低。
动态代理
- 动态代理和静态代理的角色一样
- 动态代理的代理类是动态生成的,不是我们直接写好的
- 动态代理分为两大类:
- 基于接口---JDK动态代理(我们使用的就是JDK动态代理)
- 基于类:cglib
- Java字节码实现:Javasist
- 需要了解两个类:Proxy:代理;InvocationHandler:调用处理程序


ProxyInvocationHandler.class(代理类的处理程序,负责生成代理类并返回)
package com.test.service;
import com.test.demo01.Rent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object tgart;
public void setTgart(Object tgart) {
this.tgart = tgart;
}
//生成得到的代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),tgart.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质就是通过反射机制实现的。
seeHouse();
Object result = method.invoke(tgart,args);
fare();
return result;
}
public void seeHouse(){
System.out.println("中介带看房子");
}
public void fare(){
System.out.println("中介带看房子");
}
}
MyTest3.class
import com.test.demo01.Host;
import com.test.demo01.Rent;
import com.test.service.ProxyInvocationHandler;
public class MyTest3 {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色:现在没有
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色,来处理我们要调用的接口对象
pih.setTgart(host);
Rent proxy = (Rent) pih.getProxy();//这里的Proxy就是动态生成的,不是自己写的
proxy.Rent();
//意思就是,动态的创建了一个代理类,然后代理类可以调用被程序处理角色所具有的方法,然后还可以自己添加附属属性。
}
}
MyTest4.class
import com.test.demo02.ProxyInvocationHandler;
import com.test.demo02.UserService;
import com.test.demo02.UserServiceImpl;
import java.lang.reflect.Proxy;
public class MyTest4 {
public static void main(String[] args) {
UserServiceImpl userserviceimpl = new UserServiceImpl();
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//注入被代理的真实角色
pih.setTgart(userserviceimpl);
//获取生成的代理对象 代理的类型是接口
UserService proxy = (UserService) pih.getProxy();
//使用代理对象调用真实角色所具有的方法
proxy.delete();
}
}
测试类与接口:
UserService.class
package com.test.demo02;
public interface UserService {
void add();
void delete();
void update();
void select();
}
UserServiceImpl.class
package com.test.demo02;
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("添加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("更新了一个用户");
}
public void select() {
System.out.println("查询了用户");
}
}
ProxyInvocationHandler.class
package com.test.demo02;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
//被代理的接口
private Object tgart;
public void setTgart(Object tgart) {
this.tgart = tgart;
}
//生成得到的代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),tgart.getClass().getInterfaces(),this);
}
//处理代理实例,并返回结果
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//动态代理的本质就是通过反射机制实现的。
//获取代理类调用的方法的名称
log(method.getName());
Object result = method.invoke(tgart,args);
return result;
}
public void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
AOP
什么是AOP(一种横向编程的思想,在不影响原有的业务的基础上实现功能增强)
面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
- 在使用AOP之前需要先引入AOP的依赖

AOP在Spring中的作用:
提供声明式业务;允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分就是横切关注点。如日志、安全、缓存、事务等。
- 切面(ASPECT):横切关注点被模块化的特殊对象,即,它是一个类(Log.class)
- 通知(Advice):切面必须要完成的工作,即,它是类中的一个方法(Log.class中的method)
- 目标(Target):被通知对象。(真实角色)
- 代理(Proxy):向目标对象应用通知之后创建的对象。(代理对象)
- 切入点(PointCut):切面通知执行的“地点”的定义。(代理对象要执行的真实角色中的哪个方法)
- 连接点(JoinPoint):与切入点匹配的执行结点

使用Spring实现AOP
【重点】使用AOP织入之前,需要导入依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
【重点】在使用之前,在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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
</beans>
AOP中切入点中execution表达式的使用
<aop:pointcut id="userlog" expression="execution(* com.test.service.UserServiceImpl.*(..))"/>

实现切面编程的三种方式
方法1:使用Spring的API接口【主要SpringAPI接口】
方法2:自定义来实现AOP【主要是切面定义】
方法3:使用注解实现AOP
测试类:
UserService.class
package com.test.service;
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
package com.test.service;
public class UserServiceImpl implements UserService{
public void add() {
System.out.println("增加了一个用户");
}
public void delete() {
System.out.println("删除了一个用户");
}
public void update() {
System.out.println("修改了一个用户");
}
public void select() {
System.out.println("查询了一个用户");
}
}
UserServiceImpl.class
package com.test.service;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
//在执行目标对象方法之前执行
public class BeforeLog implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//objects:参数
//o:目标对象
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"执行了"+method.getName()+"方法");
}
}
BeforeLog.class
package com.test.service;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
//在执行目标对象方法之前执行
public class BeforeLog implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//objects:参数
//o:目标对象
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println(o.getClass().getName()+"执行了"+method.getName()+"方法");
}
}
AfterLog.class
package com.test.service;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
//在目标对象方法执行后执行
public class AfterLog implements AfterReturningAdvice {
//returnValue:返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName()+"执行了"+method.getName()+"方法,"+"返回值为:"+returnValue);
}
}
DiyPointCout.class
package com.test.service;
public class DiyPointCout {
public void before(){
System.out.println("---在方法之前执行了---");
}
public void after(){
System.out.println("---在方法之后执行了---");
}
}
MyTest.class
import com.test.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 userServiceImpl = context.getBean("userServiceImpl", UserService.class);
userServiceImpl.delete();
}
}
xml文件的配置,两种方式实现的主要区别就在于aop.config的配置
<?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"
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">
<!--注册bean-->
<bean id="userServiceImpl" class="com.test.service.UserServiceImpl"/>
<bean id="beforeLog" class="com.test.service.BeforeLog"/>
<bean id="afterLog" class="com.test.service.AfterLog"/>
<!--方式1:原生的Spring API接口-->
<!--配置AOP,需要导入约束-->
<aop:config>
<!--切入点 expression:表达式 execution:要执行的位置-->
<aop:pointcut id="userlog" expression="execution(* com.test.service.UserServiceImpl.*(..))"/>
<!--执行环绕增强-->
<aop:advisor advice-ref="beforeLog" pointcut-ref="userlog"/>
<aop:advisor advice-ref="afterLog" pointcut-ref="userlog"/>
</aop:config>
<!--方式2:自定义切点-->
<bean id="diy" class="com.test.service.DiyPointCout"></bean>
<aop:config>
<!--编织切面-->
<aop:aspect ref="diy">
<!--编织切点-->
<aop:pointcut id="userlogdiy" expression="execution(* com.test.service.UserServiceImpl.*(..))"/>
<!--切点前增强-->
<aop:before method="before" pointcut-ref="userlogdiy"/>
<!--切点后增强-->
<aop:after method="after" pointcut-ref="userlogdiy"/>
</aop:aspect>
</aop:config>
</beans>
方式3(测试类使用上面的UserService.class UserServiceImpl.class MyTest.class)
AnnocationPointCut.class
package com.test.diy;
import org.aspectj.lang.ProceedingJoinPoint;
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 AnnocationPointCut {
@Before("execution(* com.test.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("---方法执行前---");
}
@After("execution(* com.test.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("---方法执行后---");
}
//使用环绕增强需要传递一个参数,代表我们要获取处理的切入点
@Around("execution(* com.test.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
//执行方法
Object proceed = jp.proceed();
System.out.println("环绕后");
}
}
applicationContext.xml的配置
<!--注册bean-->
<bean id="userServiceImpl" class="com.test.service.UserServiceImpl"/>
<bean id="beforeLog" class="com.test.service.BeforeLog"/>
<bean id="afterLog" class="com.test.service.AfterLog"/>
<!--方式3:使用注解实现AOP-->
<bean id="annocationPointCut" class="com.test.diy.AnnocationPointCut"/>
<!--开启注解支持-->
<!--Spring的动态代理默认使用JDK(代理接口)实现 proxy-target-class="false"(这是默认的)
如果这个参数为true的话那么是使用cglib(代理类)实现proxy-target-class="true"
实现的功能是一样的
-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

浙公网安备 33010602011771号