spring的AOP

29 篇文章 0 订阅

AOP

一、AOP介绍介绍

1、什么是AOP

l  在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。

利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

l  AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码

l  经典应用:事务管理、性能监视、安全检查、缓存 、日志等

l  Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码

l  AspectJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,

AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入

 

纵向继承:
 
使用代理:
 

2、AOP实现原理

l  aop底层将采用代理机制进行实现。

l  接口 + 实现类:spring采用 jdk 的动态代理Proxy。

l  实现类:spring 采用 cglib字节码增强

 

 

3、AOP术语

1.target:目标类,需要被代理的类。例如:UserService

2.Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法

3.PointCut 切入点:已经被增强的连接点。例如:addUser()

4.advice 通知/增强,增强代码。例如:after、before

5. Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.

6.proxy 代理类

7. Aspect(切面): 是切入点pointcut和通知advice的结合

       一个线是一个特殊的面。

       一个切入点和一个通知,组成成一个特殊的面。

 

 

二、手动方式

1、JDK动态代理

l  JDK动态代理 对“装饰者”设计模式简化。使用前提:必须有接口

1.目标类:接口 + 实现类

2.切面类:用于存放通知 MyAspect

3.工厂类:编写工厂生成代理

4.测试

UserService:
package com.hcx.a_proxy.a_jdk;

public interface UserService {
	
	public void addUser();
	public void updateUser();
	public void deleteUser();

}

 
 
UserServiceImpl:
package com.hcx.a_proxy.a_jdk;

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		System.out.println("a_proxy.a_jdk addUser");
	}

	@Override
	public void updateUser() {
		System.out.println("a_proxy.a_jdk updateUser");

	}

	@Override
	public void deleteUser() {

		System.out.println("a_proxy.a_jdk deleteUser");
	}

}

 
 
MyAspect(切面类):
package com.hcx.a_proxy.a_jdk;

public class MyAspect {
	
	public void before(){
		System.out.println("鸡首");
	}
	
	public void after(){
		System.out.println("牛后");
	}

}

 
 
MyBeanFactory:
package com.hcx.a_proxy.a_jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBeanFactory {
	
	public static UserService createService(){
		//1 目标类
		final UserService userService = new UserServiceImpl();
		//2切面类
		final MyAspect myAspect = new MyAspect();
		/* 3 代理类:将目标类(切入点)和 切面类(通知) 结合 --> 切面
		 * 	Proxy.newProxyInstance
		 * 		参数1:loader ,类加载器,动态代理类 运行时创建,任何类都需要类加载器将其加载到内存。
		 * 			一般情况:当前类.class.getClassLoader();
		 * 					目标类实例.getClass().get...
		 * 		参数2:Class[] interfaces 代理类需要实现的所有接口
		 * 			方式1:目标类实例.getClass().getInterfaces()  ;注意:只能获得自己接口,不能获得父元素接口
		 * 			方式2:new Class[]{UserService.class}   
		 * 			例如:jdbc 驱动  --> DriverManager  获得接口 Connection
		 * 		参数3:InvocationHandler  处理类,接口,必须进行实现类,一般采用匿名内部
		 * 			提供 invoke 方法,代理类的每一个方法执行时,都将调用一次invoke
		 * 				参数3.1:Object proxy :代理对象
		 * 				参数3.2:Method method : 代理对象当前执行的方法的描述对象(反射)
		 * 					执行方法名:method.getName()
		 * 					执行方法:method.invoke(对象,实际参数)
		 * 				参数3.3:Object[] args :方法实际参数
		 * 
		 */
		UserService proxService = (UserService)Proxy.newProxyInstance(
								MyBeanFactory.class.getClassLoader(), 
								userService.getClass().getInterfaces(), 
								new InvocationHandler() {
									
									@Override
									public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
										
										//前执行
										myAspect.before();
										
										//执行目标类的方法
										Object obj = method.invoke(userService, args);
										
										//后执行
										myAspect.after();
										
										return obj;
									}
								});
		
		return proxService;
	}

}
 

TestJDK:
package com.hcx.a_proxy.a_jdk;

import org.junit.Test;

public class TestJDK {
	
	@Test
	public void demo01(){
		UserService userService = MyBeanFactory.createService();
		userService.addUser();
		userService.updateUser();
		userService.deleteUser();
	}

}
 

代理类的底层:
 


2、CGLIB字节码增强

没有接口,只有实现类。

采用字节码增强框架 cglib,在运行时 创建目标类的子类,从而对目标类进行增强。

导入jar包:

       自己导包(了解):

              核心:hibernate-distribution-3.6.10.Final\lib\bytecode\cglib\cglib-2.2.jar

              依赖:struts-2.3.15.3\apps\struts2-blank\WEB-INF\lib\asm-3.3.jar

       spring-core..jar已经整合以上两个内容:

UserServiceImpl:

 

package com.hcx.a_proxy.b_cglib;

public class UserServiceImpl {

	public void addUser() {
		System.out.println("a_proxy.b_cglib addUser");
	}

	public void updateUser() {
		System.out.println("a_proxy.b_cglib updateUser");

	}

	public void deleteUser() {

		System.out.println("a_proxy.b_cglib deleteUser");
	}

}
 

 

MyAspect:

 

package com.hcx.a_proxy.b_cglib;

public class MyAspect {
	
	public void before(){
		System.out.println("鸡首2");
	}
	
	public void after(){
		System.out.println("牛后2");
	}

}
 

 

MyBeanFactory:

 

package com.hcx.a_proxy.b_cglib;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;


public class MyBeanFactory {
	
	public static UserServiceImpl createService(){
		//1 目标类
		final UserServiceImpl userService = new UserServiceImpl();
		//2切面类
		final MyAspect myAspect = new MyAspect();
		// 3.代理类 ,采用cglib,底层创建目标类的子类
		//3.1 核心类
		Enhancer enhancer = new Enhancer();
		//3.2 确定父类
		enhancer.setSuperclass(userService.getClass());
		/* 3.3 设置回调函数 , MethodInterceptor接口 等效 jdk InvocationHandler接口
		 * 	intercept() 等效 jdk  invoke()
		 * 		参数1、参数2、参数3:与invoke一样:
		 *              参数1:Object proxy :代理对象
		 * 				参数2:Method method : 代理对象当前执行的方法的描述对象(反射)
		 * 					执行方法名:method.getName()
		 * 					执行方法:method.invoke(对象,实际参数)
		 * 				参数3:Object[] args :方法实际参数
		 * 		参数4:methodProxy 方法的代理
		 * 		
		 * 
		 */
		enhancer.setCallback(new MethodInterceptor(){

			@Override
			public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
				
				//前
				myAspect.before();
				
				//执行目标类的方法
				Object obj = method.invoke(userService, args);
				// * 执行代理类的父类 ,执行目标类 (目标类和代理类 父子关系)
				methodProxy.invokeSuper(proxy, args);
				
				//后
				myAspect.after();
				
				return obj;
			}
		});
		//3.4 创建代理
		UserServiceImpl proxService = (UserServiceImpl) enhancer.create();
		
		return proxService;
	}

}
 

 

TestCglib:

 

package com.hcx.a_proxy.b_cglib;

import org.junit.Test;

public class TestCglib {
	
	@Test
	public void demo01(){
		UserServiceImpl userService = MyBeanFactory.createService();
		userService.addUser();
		userService.updateUser();
		userService.deleteUser();
	}

}
 

 

三、AOP联盟通知类型

l  AOP联盟为通知Advice定义了org.aopalliance.aop.Advice

l  Spring按照通知Advice在目标类方法的连接点位置,可以分为5类:

•    前置通知 org.springframework.aop.MethodBeforeAdvice

•   在目标方法执行前实施增强

•   后置通知 org.springframework.aop.AfterReturningAdvice

•   在目标方法执行后实施增强

•    环绕通知 org.aopalliance.intercept.MethodInterceptor

•   在目标方法执行前后实施增强

•    异常抛出通知 org.springframework.aop.ThrowsAdvice

•   在方法抛出异常后实施增强

•    引介通知 org.springframework.aop.IntroductionInterceptor

•  在目标类中添加一些新的方法和属性
 
环绕通知,必须手动执行目标方法
try{
   //前置通知
   //执行目标方法
   //后置通知
} catch(){
   //抛出异常通知
}

 

四、spring编写代理:半自动

l  让spring 创建代理对象,从spring容器中手动的获取代理对象。

l  导入jar包:

       核心:4+1

       AOP:AOP联盟(规范)、spring-aop (实现)

 
UserService:
package com.hcx.b_factory_bean;

public interface UserService {
	
	public void addUser();
	public void updateUser();
	public void deleteUser();

}
 
UserServiceImpl:
package com.hcx.b_factory_bean;

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		System.out.println("b_factory_bean addUser");
	}

	@Override
	public void updateUser() {
		System.out.println("b_factory_bean updateUser");

	}

	@Override
	public void deleteUser() {

		System.out.println("b_factory_bean deleteUser");
	}

}

 
 
MyAspect:
package com.hcx.b_factory_bean;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
 * * 采用“环绕通知” MethodInterceptor
 *
 */
public class MyAspect implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		
		System.out.println("前3");
		
		//手动执行目标方法
		Object obj = mi.proceed();
		
		System.out.println("后3");
		return obj;
	}
}

 
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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
       					   http://www.springframework.org/schema/beans/spring-beans.xsd">
	<!-- 1 创建目标类 -->
	<bean id="userServiceId" class="com.hcx.b_factory_bean.UserServiceImpl"></bean>
	<!-- 2 创建切面类 -->
	<bean id="myAspectId" class="com.hcx.b_factory_bean.MyAspect"></bean>

	<!-- 3 创建代理类 
		* 使用工厂bean FactoryBean ,底层调用 getObject() 返回特殊bean
		* ProxyFactoryBean 用于创建代理工厂bean,生成特殊代理对象
			interfaces : 确定接口们
				通过<array>可以设置多个值
				只有一个值时,value=""
			target : 确定目标类
			interceptorNames : 通知 切面类的名称,类型String[],如果设置一个值 value=""
			optimize :强制使用cglib
				<property name="optimize" value="true"></property>
		底层机制
			如果目标类有接口,采用jdk动态代理
			如果没有接口,采用cglib 字节码增强
			如果声明 optimize = true ,无论是否有接口,都采用cglib
		
	-->
	<bean id="proxyServiceId" class="org.springframework.aop.framework.ProxyFactoryBean">
		<property name="interfaces" value="com.hcx.b_factory_bean.UserService"></property>
		<property name="target" ref="userServiceId"></property>
		<property name="interceptorNames" value="myAspectId"></property>
	</bean>
</beans>

 
 
TestFactoryBean:
package com.hcx.b_factory_bean;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestFactoryBean {
	
	@Test
	public void demo01(){
		String xmlPath = "com/hcx/b_factory_bean/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		
		//获得代理类
		UserService userService = (UserService) applicationContext.getBean("proxyServiceId");
		userService.addUser();
		userService.updateUser();
		userService.deleteUser();
	}

}
缺点:写死了:

五、spring aop编程:全自动

l  从spring容器获得目标类,如果配置aop,spring将自动生成代理。

l  要确定目标类,aspectj 切入点表达式,导入jar包

       spring-framework-3.0.2.RELEASE-dependencies\org.aspectj\com.springsource.org.aspectj.weaver\1.6.8.RELEASE

导包:

 
spring配置:
 
UserService:
package com.hcx.c_spring_aop;

public interface UserService {
	
	public void addUser();
	public void updateUser();
	public void deleteUser();

}

 
UserServiceImpl:
package com.hcx.c_spring_aop;

public class UserServiceImpl implements UserService {

	@Override
	public void addUser() {
		System.out.println("c_spring_aop addUser");
	}

	@Override
	public void updateUser() {
		System.out.println("c_spring_aop updateUser");

	}

	@Override
	public void deleteUser() {

		System.out.println("c_spring_aop deleteUser");
	}

}
 
MyAspect:
package com.hcx.c_spring_aop;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

/**
 * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
 * * 采用“环绕通知” MethodInterceptor
 *
 */
public class MyAspect implements MethodInterceptor {

	@Override
	public Object invoke(MethodInvocation mi) throws Throwable {
		
		System.out.println("前4");
		
		//手动执行目标方法
		Object obj = mi.proceed();
		
		System.out.println("后4");
		return obj;
	}
}

 
 
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.xsd
       					   http://www.springframework.org/schema/aop 
       					   http://www.springframework.org/schema/aop/spring-aop.xsd">
	<!-- 1 创建目标类 -->
	<bean id="userServiceId" class="com.hcx.c_spring_aop.UserServiceImpl"></bean>
	<!-- 2 创建切面类(通知) -->
	<bean id="myAspectId" class="com.hcx.c_spring_aop.MyAspect"></bean>
	<!-- 3 aop编程 
			3.1 导入命名空间
			3.2 使用 <aop:config>进行配置
					proxy-target-class="true" 声明时使用cglib代理
				<aop:pointcut> 切入点 ,从目标对象获得具体方法
				<aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
					advice-ref 通知的引用
					pointcut-ref 切入点的引用
			3.3 切入点表达式
				execution(* com.hcx.c_spring_aop.*.*(..))
				选择方法         返回值任意   包                                             类名任意   方法名任意   参数任意
		
	-->
	<aop:config proxy-target-class="true">
		<aop:pointcut expression="execution(* com.hcx.c_spring_aop.*.*(..))" id="myPointCut"/>
		<aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
	</aop:config>
</beans>

 
 
TestSpringAOP:
package com.hcx.c_spring_aop;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpringAOP {
	
	@Test
	public void demo01(){
		String xmlPath = "com/hcx/c_spring_aop/beans.xml";
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
		
		//获得目标类
		UserService userService = (UserService) applicationContext.getBean("userServiceId");
		userService.addUser();
		userService.updateUser();
		userService.deleteUser();
	}

}

 
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值