【SpringDay03之AOP】

动态代理

在学习Spring的时候,我们知道Spring主要有两大思想,一个是IoC,另一个就是AOP,对于IoC,依赖注入就不用多说了,而对于Spring的核心AOP来说,我们不但要知道怎么通过AOP来满足的我们的功能,我们更需要学习的是其底层是怎么样的一个原理,而AOP的原理就是java的动态代理机制。

动态代理的特点

字节码随用随创建,随用随加载。
它与静态代理的区别也在于此。因为静态代理是字节码一上来就创建好,并完成加载。
装饰者模式就是静态代理的一种体现。

动态代理常用的有两种方式

  • 基于接口的动态代理:
    提供者:JDK官方的Proxy类。
    要求:被代理类最少实现一个接口。
  • 基于子类的动态代理:
    提供者:第三方的CGLib,如果报asmxxxx异常,需要导入asm.jar。
    要求:被代理类不能用final修饰的类(最终类)

使用JDK官方的Proxy类创建代理对象

此处我们使用的是一个演员的例子:
在很久以前,演员和剧组都是直接见面联系的。没有中间人环节。
而随着时间的推移,产生了一个新兴职业:经纪人(中间人),这个时候剧组再想找演员就需要通过经纪人来找了。下面我们就用代码演示出来。

/**
 * 一个经纪公司的要求:
 * 		能做基本的表演和危险的表演
*/
public interface IActor {
	/**
	 * 基本演出
	 * @param money
	 */
	public void basicAct(float money);
	/**
	 * 危险演出
	 * @param money
	 */
	public void dangerAct(float money);
}

/**
 * 一个演员
 */
//实现了接口,就表示具有接口中的方法实现。即:符合经纪公司的要求
public class Actor implements IActor{
	
	public void basicAct(float money){
		System.out.println("拿到钱,开始基本的表演:"+money);
	}
	
	public void dangerAct(float money){
		System.out.println("拿到钱,开始危险的表演:"+money);
	}
}

public class Client {
	
	public static void main(String[] args) {
		//一个剧组找演员:
		final Actor actor = new Actor();//直接
		
		/**
		 * 代理:
		 * 	间接。
		 * 获取代理对象:
		 * 	要求:
		 * 	 被代理类最少实现一个接口
		 * 创建的方式
		 *   Proxy.newProxyInstance(三个参数)
		 * 参数含义:
		 * 	ClassLoader:和被代理对象使用相同的类加载器。
		 *  Interfaces:和被代理对象具有相同的行为。实现相同的接口。
		 *  InvocationHandler:如何代理。
		 *  		策略模式:使用场景是:
		 *  					数据有了,目的明确。
		 *  					如何达成目标,就是策略。
		 *  			
		 */
		IActor proxyActor = (IActor) Proxy.newProxyInstance(
										actor.getClass().getClassLoader(), 
										actor.getClass().getInterfaces(), 
										new InvocationHandler() {
				/**
				 * 执行被代理对象的任何方法,都会经过该方法。
				 * 此方法有拦截的功能。
				 * 
				 * 参数:
				 * 	proxy:代理对象的引用。不一定每次都用得到
				 * 	method:当前执行的方法对象
				 * 	args:执行方法所需的参数
				 * 返回值:
				 * 	当前执行方法的返回值
				 */
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					String name = method.getName();
					Float money = (Float) args[0];
					Object rtValue = null;
					//每个经纪公司对不同演出收费不一样,此处开始判断
					if("basicAct".equals(name)){
						//基本演出,没有2000不演
						if(money > 2000){
							//看上去剧组是给了8000,实际到演员手里只有4000
							//这就是我们没有修改原来basicAct方法源码,对方法进行了增强
							rtValue = method.invoke(actor, money/2);
						}
					}
					if("dangerAct".equals(name)){
						//危险演出,没有5000不演
						if(money > 5000){
							//看上去剧组是给了50000,实际到演员手里只有25000
							//这就是我们没有修改原来dangerAct方法源码,对方法进行了增强
							rtValue = method.invoke(actor, money/2);
						}
					}
					return rtValue;
				}
		});
		//没有经纪公司的时候,直接找演员。
//		actor.basicAct(1000f);
//		actor.dangerAct(5000f);
		
		//剧组无法直接联系演员,而是由经纪公司找的演员
		proxyActor.basicAct(8000f);
		proxyActor.dangerAct(50000f);
	}
}

使用CGLib的Enhancer类创建代理对象

还是那个演员的例子,只不过不让他实现接口。

/**
 * 一个演员
*/
public class Actor{//没有实现任何接口
	
	public void basicAct(float money){
		System.out.println("拿到钱,开始基本的表演:"+money);
	}
	
	public void dangerAct(float money){
		System.out.println("拿到钱,开始危险的表演:"+money);
	}
}

public class Client {
	/**
	 * 基于子类的动态代理
	 * 	要求:
	 * 		被代理对象不能是最终类
	 * 	用到的类:
	 * 		Enhancer
	 * 	用到的方法:
	 * 		create(Class, Callback)
	 * 	方法的参数:
	 * 		Class:被代理对象的字节码
	 * 		Callback:如何代理
	 * @param args
	 */
	public static void  main(String[] args) {
		final Actor actor = new Actor();
		
		Actor cglibActor = (Actor) Enhancer.create(actor.getClass(),
							new MethodInterceptor() {
			/**
			 * 执行被代理对象的任何方法,都会经过该方法。在此方法内部就可以对被代理对象的任何方法进行增强。
			 * 
			 * 参数:
			 * 	前三个和基于接口的动态代理是一样的。
			 * 	MethodProxy:当前执行方法的代理对象。
			 * 返回值:
			 * 	当前执行方法的返回值
			 */
			@Override
			public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
				String name = method.getName();
				Float money = (Float) args[0];
				Object rtValue = null;
				if("basicAct".equals(name)){
					//基本演出
					if(money > 2000){
						rtValue = method.invoke(actor, money/2);
					}
				}
				if("dangerAct".equals(name)){
					//危险演出
					if(money > 5000){
						rtValue = method.invoke(actor, money/2);
					}
				}
				return rtValue;
			}
		});		
		cglibActor.basicAct(10000);
		cglibActor.dangerAct(100000);
	}
}

AOP

Spring 框架的一个关键组件是面向方面的编程(AOP)框架。面向方面的编程需要把程序逻辑分解成不同的部分称为所谓的关注点。跨一个应用程序的多个点的功能被称为横切关注点,这些横切关注点在概念上独立于应用程序的业务逻辑。有各种各样的常见的很好的方面的例子,如日志记录、审计、声明式事务、安全性和缓存等。
在 OOP 中,关键单元模块度是类,而在 AOP 中单元模块度是方面。依赖注入帮助你对应用程序对象相互解耦和 AOP 可以帮助你从它们所影响的对象中对横切关注点解耦。AOP 是像编程语言的触发物,如 Perl,.NET,Java 或者其他。
Spring AOP 模块提供拦截器来拦截一个应用程序,例如,当执行一个方法时,你可以在方法执行之前或之后添加额外的功能。

AOP术语

这些术语并不特定于 Spring,而是与 AOP 有关的。在这里插入图片描述
Joinpoint(连接点):
所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。
Pointcut(切入点):
所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。
Advice(通知/增强):
所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。
Introduction(引介):
引介是一种特殊的通知在不修改类代码的前提下, Introduction可以在运行期为类动态地添加一些方法或Field。
Target(目标对象):
代理的目标对象。
Weaving(织入):
是指把增强应用到目标对象来创建新的代理对象的过程。
spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。
Proxy(代理):
一个类被AOP织入增强后,就产生一个结果代理类。
Aspect(切面):
是切入点和通知(引介)的结合。

通知的类型

Spring 方面可以使用下面提到的五种通知工作:在这里插入图片描述

基于XML的AOP配置

环境搭建

第一步:准备客户的业务层和接口(需要增强的类)

/**
 * 客户的业务层接口
*/
public interface ICustomerService {
	
	/**
	 * 保存客户
	 */
	void saveCustomer();
	
	/**
	 * 修改客户
	 * @param i
	 */
	void updateCustomer(int i);
}

/**
 * 客户的业务层实现类
 */
public class CustomerServiceImpl implements ICustomerService {

	@Override
	public void saveCustomer() {
		System.out.println("调用持久层,执行保存客户");
	}

	@Override
	public void updateCustomer(int i) {
		System.out.println("调用持久层,执行修改客户");
	}
}

第二步:拷贝必备的jar包到工程的lib目录

第三步:创建spring的配置文件并导入约束

<?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">

</beans>

第四步:把客户的业务层配置到spring容器中

<!-- 把资源交给spring来管理 -->
<bean id="customerService" class="com.itheima.service.impl.CustomerServiceImpl"/>

第五步:制作通知(增强的类)

/**
 * 一个记录日志的工具类
*/
public class Logger {
	/**
	 * 期望:此方法在业务核心方法执行之前,就记录日志
	 */
	public void beforePrintLog(){
		System.out.println("Logger类中的printLog方法开始记录日志了。。。。");
	}
}

配置步骤

第一步:把通知类用bean标签配置起来

<!-- 把有公共代码的类也让spring来管理(把通知类也交给spring来管理) -->
<bean id="logger" class="com.itheima.util.Logger"></bean>

第二步:使用aop:config声明aop配置

<!-- aop的配置 -->
<aop:config>
	<!-- 配置的代码都写在此处 -->	
</aop:config>

第三步:使用aop:aspect配置切面

<!-- 配置切面 :此标签要出现在aop:config内部
	id:给切面提供一个唯一标识
	ref:引用的是通知类的bean的id
-->
<aop:aspect id="logAdvice" ref="logger">
		<!--配置通知的类型要写在此处-->
</aop:aspect>

第四步:使用aop:before配置前置通知

<!-- 用于配置前置通知:指定增强的方法在切入点方法之前执行 
		method:用于指定通知类中的增强方法名称
		ponitcut-ref:用于指定切入点的表达式的引用	
-->
<aop:before method="beforePrintLog" pointcut-ref="pt1"/>

第五步:使用aop:pointcut配置切入点表达式

<aop:pointcut expression="execution(public void com.itheima.service.impl.CustomerServiceImpl.saveCustomer())" 
id="pt1"/>

切入点表达式说明

在这里插入图片描述

常用标签

标签作用属性
<aop:config>用于声明开始aop的配置
<aop:aspect>用于配置切面id:给切面提供一个唯一标识。ref:引用配置好的通知类bean的id
<aop:pointcut>用于配置切入点表达式expression:用于定义切入点表达式。id:用于给切入点表达式提供一个唯一标识。
<aop:before>用于配置前置通知method:指定通知中方法的名称。pointcut:定义切入点表达式.pointcut-ref:指定切入点表达式的引用
<aop:after-returning>用于配置后置通知method:指定通知中方法的名称。pointcut:定义切入点表达式.pointcut-ref:指定切入点表达式的引用
<aop:after-throwing>用于配置异常通知method:指定通知中方法的名称。pointcut:定义切入点表达式.pointcut-ref:指定切入点表达式的引用
<aop:after>用于配置最终通知method:指定通知中方法的名称。pointcut:定义切入点表达式.pointcut-ref:指定切入点表达式的引用
<aop:around>用于配置环绕通知method:指定通知中方法的名称。pointcut:定义切入点表达式.pointcut-ref:指定切入点表达式的引用

环绕通知的特殊说明

在这里插入图片描述
示例:
这里是 Logging.java 文件的内容。这实际上是 aspect 模块的一个示例,它定义了在各个点调用的方法。

package com.tutorialspoint;
public class Logging {
   /** 
    * This is the method which I would like to execute
    * before a selected method execution.
    */
   public void beforeAdvice(){
      System.out.println("Going to setup student profile.");
   }
   /** 
    * This is the method which I would like to execute
    * after a selected method execution.
    */
   public void afterAdvice(){
      System.out.println("Student profile has been setup.");
   }
   /** 
    * This is the method which I would like to execute
    * when any method returns.
    */
   public void afterReturningAdvice(Object retVal){
      System.out.println("Returning:" + retVal.toString() );
   }
   /**
    * This is the method which I would like to execute
    * if there is an exception raised.
    */
   public void AfterThrowingAdvice(IllegalArgumentException ex){
      System.out.println("There has been an exception: " + ex.toString());   
   }  
}

下面是 Student.java 文件的内容:

package com.tutorialspoint;
public class Student {
   private Integer age;
   private String name;
   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      System.out.println("Age : " + age );
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      System.out.println("Name : " + name );
      return name;
   }  
   public void printThrowException(){
       System.out.println("Exception raised");
       throw new IllegalArgumentException();
   }
}

下面是 MainApp.java 文件的内容:

package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = 
             new ClassPathXmlApplicationContext("Beans.xml");
      Student student = (Student) context.getBean("student");
      student.getName();
      student.getAge();      
      student.printThrowException();
   }
}

下面是配置文件 Beans.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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
      <aop:aspect id="log" ref="logging">
         <aop:pointcut id="selectAll" 
         expression="execution(* com.tutorialspoint.*.*(..))"/>
         <aop:before pointcut-ref="selectAll" method="beforeAdvice"/>
         <aop:after pointcut-ref="selectAll" method="afterAdvice"/>
         <aop:after-returning pointcut-ref="selectAll" 
                              returning="retVal"
                              method="afterReturningAdvice"/>
         <aop:after-throwing pointcut-ref="selectAll" 
                             throwing="ex"
                             method="AfterThrowingAdvice"/>
      </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id="student" class="com.tutorialspoint.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>      
   </bean>

   <!-- Definition for logging aspect -->
   <bean id="logging" class="com.tutorialspoint.Logging"/> 

</beans>

一旦你已经完成的创建了源文件和 bean 配置文件,让我们运行一下应用程序。如果你的应用程序一切都正常的话,这将会输出以下消息:

Going to setup student profile.
Name : Zara
Student profile has been setup.
Returning:Zara
Going to setup student profile.
Age : 11
Student profile has been setup.
Returning:11
Going to setup student profile.
Exception raised
Student profile has been setup.
There has been an exception: java.lang.IllegalArgumentException
.....
other exception content

让我们来解释一下上面定义的在 com.tutorialspoint 中 选择所有方法的 。让我们假设一下,你想要在一个特殊的方法之前或者之后执行你的建议,你可以通过替换使用真实类和方法名称的切入点定义中的星号(*)来定义你的切入点来缩短你的执行。

<?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-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

   <aop:config>
   <aop:aspect id="log" ref="logging">
      <aop:pointcut id="selectAll" 
      expression="execution(* com.tutorialspoint.Student.getName(..))"/>
      <aop:before pointcut-ref="selectAll" method="beforeAdvice"/>
      <aop:after pointcut-ref="selectAll" method="afterAdvice"/>
   </aop:aspect>
   </aop:config>

   <!-- Definition for student bean -->
   <bean id="student" class="com.tutorialspoint.Student">
      <property name="name"  value="Zara" />
      <property name="age"  value="11"/>      
   </bean>

   <!-- Definition for logging aspect -->
   <bean id="logging" class="com.tutorialspoint.Logging"/> 

</beans>

如果你想要执行通过这些更改之后的示例应用程序,这将会输出以下消息:

Going to setup student profile.
Name : Zara
Student profile has been setup.
Age : 11
Exception raised
.....
other exception content

基于注解的AOP配置

环境搭建

第一步:准备客户的业务层和接口并用注解配置(需要增强的类)

第二步:拷贝必备的jar包到工程的lib目录

第三步:创建spring的配置文件并导入约束

第四步:把资源使用注解让spring来管理

/**
 * 客户的业务层实现类
 */
@Service("customerService")
public class CustomerServiceImpl implements ICustomerService {

	@Override
	public void saveCustomer() {
		System.out.println("调用持久层,执行保存客户");
	}
	@Override
	public void updateCustomer(int i) {
		System.out.println("调用持久层,执行修改客户");
	}
}

第五步:在配置文件中指定spring要扫描的包

<!-- 告知spring,在创建容器时要扫描的包 -->
<context:component-scan base-package="com.itheima"></context:component-scan> 

配置步骤

第一步:把通知类也使用注解配置

/**
 * 一个记录日志的工具类
 */
@Component("logger")
public class Logger {
	/**
	 * 期望:此方法在业务核心方法执行之前,就记录日志
	 * 前置通知
	 */
	public void beforePrintLog(){
		System.out.println("前置通知:Logger类中的printLog方法开始记录日志了");
	}
}

第二步:在通知类上使用@Aspect注解声明为切面

/**
 * 一个记录日志的工具类
 */
@Component("logger")
@Aspect//表明当前类是一个切面类
public class Logger {
	/**
	 * 期望:此方法在业务核心方法执行之前,就记录日志
	 * 前置通知
	 */
	public void beforePrintLog(){
		System.out.println("前置通知:Logger类中的printLog方法开始记录日志了");
	}
}

第三步:在增强的方法上使用@Before注解配置前置通知

/**
	 * 期望:此方法在业务核心方法执行之前,就记录日志
	 * 前置通知
	 */
	@Before("execution(* com.itheima.service.impl.*.*(..))")//表示前置通知
	public void beforePrintLog(){
		System.out.println("前置通知:Logger类中的printLog方法开始记录日志了");
	}

第四步:在spring配置文件中开启spring对注解AOP的支持

<!-- 开启spring对注解AOP的支持 -->
<aop:aspectj-autoproxy/>

常用注解

@Aspect
作用:把当前类声明为切面类。
@Before
作用:把当前方法看成是前置通知。
属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。 @AfterReturning
作用:把当前方法看成是后置通知。
属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。 @AfterThrowing
作用:把当前方法看成是异常通知。
属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。
@After
作用:把当前方法看成是最终通知。
属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。
@Around
作用:把当前方法看成是环绕通知。
属性:value:用于指定切入点表达式,还可以指定切入点表达式的引用。
@Pointcut
作用:指定切入点表达式
属性:value:指定表达式的内容

不使用XML的配置方法

配置一个SpringConfiguration类即可

@Configuration
@ComponentScan(basePackages="com.itheima")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值