spring(2)面向切面编程(AOP)、Aspect框架的理解与使用

本文详细介绍了Spring的面向切面编程(AOP)概念,包括AOP术语解析,动态代理的JDK与CGLIB实现,以及Spring AOP的半自动和全自动编程。此外,还探讨了使用AspectJ框架(XML与注解方式)实现AOP的方法,为读者提供了全面的AOP实践指导。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、什么是面向切面编程(AOP)?

  • 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
  • AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码
  • 经典应用:事务管理、性能监视、安全检查、缓存 、日志等
  • Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码
  • AspectJ是一个基于Java语言的AOP框架,Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入

 

  AOP术语

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

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

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

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

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

        6.proxy 代理类

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

                一个线是一个特殊的面。

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

 

 

二、动态代理的两种方式

        JDK动态代理 == 接口+实现类

        cglib字节码增强 == 实现类

 

2.1、JDK动态代理

目标类

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

}

切面类

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

}

工厂类

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
		 * 				参数31:Object proxy :代理对象
		 * 				参数32:Method method : 代理对象当前执行的方法的描述对象(反射)
		 * 					执行方法名:method.getName()
		 * 					执行方法:method.invoke(对象,实际参数)
		 * 				参数33: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;
	}

}

测试

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

 

2.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 已经整合以上两个内容

 

工厂类

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一样
		 * 		参数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;
	}

}

2.4、spring编写代理:半自动

包:

目标类:

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

}

切面类:

/**
 * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
 * * 采用“环绕通知” 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;
	}
}

spring配置:

<!-- 1 创建目标类 -->
	<bean id="userService" class="com.spring.jdk.UserServiceImpl"></bean>
	<!-- 2 创建切面类 -->
	<bean id="myAspect" class="com.spring.jdk.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="proxyService" class="org.spring.jdk.ProxyFactoryBean">
		<property name="interfaces" value="com.spring.jdk.UserService"></property>
		<property name="target" ref="userService"></property>
		<property name="interceptorNames" value="myAspect"></property>
	</bean>

测试:

	@Test
	public void demo01(){
		ApplicationContext ac =new ClassPathXmlApplicationContext("ApplicationContext.xml");
		
		//获得代理类
		UserService userService = (UserService) applicationContext.getBean("proxyService");
		userService.addUser();
		userService.updateUser();
		userService.deleteUser();
	}

 

2.5、spring aop编程:全自动

包:

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">
	<!-- 1 创建目标类 -->
	<bean id="userService" class="com.spring.jdk.UserServiceImpl"></bean>
	<!-- 2 创建切面类(通知) -->
	<bean id="myAspect" class="com.spring.jdk.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.itheima.c_spring_aop.*.*(..))
			选择方法         返回值任意   包             类名任意   方法名任意   参数任意
		
	-->
	<aop:config proxy-target-class="true">
		<aop:pointcut expression="execution(* com.spring.jdk.*.*(..))" id="myPointCut"/>
		<aop:advisor advice-ref="myAspect" pointcut-ref="myPointCut"/>
	</aop:config>
</beans>

测试:

	@Test
	public void demo01(){
		ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
		
		//获得目标类
		UserService userService = (UserService) applicationContext.getBean("userService");
		userService.addUser();
		userService.updateUser();
		userService.deleteUser();
	}

2.6、使用AspectJ框架(XML方式)实现AOP

切面类:

public class MyAspect{

	public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
		System.out.println("q");
		
		Object obj = joinPoint.proceed();
		
		System.out.println("h");
		
		return obj;
	}
	
}

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

	<bean id="userServiceImpl" class="com.spring.jdk.UserServiceImpl"></bean>
	
	<bean id="myAspect" class="com.spring.jdk.MyAspect"></bean>

	<aop:config>
		<aop:aspect ref="myspect">
			<aop:pointcut expression="execution(* com.spring.jdk.*.*(..))" id="mypointcut"/>
			<aop:around method="myAround" pointcut-ref="mypointcut"/>
		</aop:aspect>
	</aop:config>

</beans>

 

2.7、使用AspectJ框架(注解方式)实现AOP

切面类:

@Component
@Aspect
public class MyAspect{

	@Pointcut("execution(* com.spring.jdk.UserServiceImpl.*(..))")
	private void myPointCut() {
		
	}
	
	
	@Around("myPointCut()")
	public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
		System.out.println("q");
		
		Object obj = joinPoint.proceed();
		
		System.out.println("h");
		
		return obj;
	}
	
}

目标类:

@Component
public class UserServiceImpl implements UserService{

	@Override
	public void add() {
		System.out.println("JDK ADD1");
	}

}

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

	<context:component-scan base-package="com.spring.jdk"></context:component-scan>
	
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值