Spring AOP 的使用

什么是AOP:
面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP是OOP(向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
关于AOP,我们要认识一下AOP的一些必须要掌握的术语。
So frist ,看有哪些术语。
1.target:目标类,需要被代理的类。例如:UserService
2.Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法
3.PointCut 切入点:已经被增强的连接点。例如:addUser()
4.advice 通知/增强,增强代码。例如:after、before
5. Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.
6.proxy 代理类
7. Aspect(切面): 是切入点pointcut和通知advice的结合
一个线是一个特殊的面。
一个切入点和一个通知,组成成一个特殊的面
1,手动模式编写代理类(手动方式了解一下即可)
1.1 jdk动态代理(需要接口)
使用beanFactory类:

     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;
        }

}
1.2 cglib代理(不需要接口)
2,spring编写代理(半自动)
由spring生成代理类,手动获取代理对象
3,springaop编程(要求掌握)
由spring生成代理类,使用aop自动代理
3.1 编写目标类

public class UserService{
  public void addUser();
  public void deleteUser();
  public void updateUser();
  }

3.2 编写切面类

    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;
}
}

3.3 spring配置
< !-- 1 创建目标类 -->

< bean  id="userServiceId" class="spring_aop.UserServiceImpl"></bean>

< !-- 2 创建切面类(通知) -->

< bean id="myAspectId" class="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(* spring_aop..(…))
选择方法 返回值任意 包 类名任意 方法名任意 参数任意

–>

<aop:config proxy-target-class="true">
	<aop:pointcut expression="execution(* spring_aop.*.*(..))" id="myPointCut"/>
	<aop:advisor advice-ref="myAspectId" pointcut-ref="myPointCut"/>
</aop:config>

测试:
@Test
public void demo01(){
String xmlPath = “spring_aop/beans.xml”;
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);

//获得目标类
UserService userService = (UserService) applicationContext.getBean("userServiceId");
userService.addUser();
userService.updateUser();
userService.deleteUser();

}
AspectJ
下面介绍AspectJ,建议使用AspectJ方式来开发AOP
AspectJ是一个基于Java语言的AOP框架
Spring2.0以后新增了对AspectJ切点表达式支持
@AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面
新版本Spring框架.
1.execution() 用于描述方法 【掌握】
语法:execution(修饰符 返回值 包.类.方法名(参数) throws异常)
修饰符,一般省略
public 公共方法
* 任意
返回值,不能省略
void 返回没有值
String 返回值字符串
* 任意
包,[省略]
com.crm 固定包
com.crm..service crm包下面子包任意 (例如:com.itheima.crm.staff.service)
com.crm… crm包下面的所有子包(含自己)
com.crm.
.service… crm包下面任意子包,固定目录service,service目录任意包
类,[省略]
UserServiceImpl 指定类
Impl 以Impl结尾
User
以User开头
* 任意
方法名,不能省略
addUser 固定方法
add* 以add开头
Do 以Do结尾
* 任意
(参数)
() 无参
(int) 一个整型
(int ,int) 两个
(…) 参数任意
throws ,可省略,一般不写。
2:AspectJ 通知类型
aop联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称。
aspectj 通知类型,只定义类型名称。已经方法格式。
个数:6种,知道5种,掌握1中。
before:前置通知(应用:各种校验)
在方法执行前执行,如果通知抛出异常,阻止方法运行
afterReturning:后置通知(应用:常规数据处理)
方法正常返回后执行,如果方法中抛出异常,通知无法执行
必须在方法执行后才执行,所以可以获得方法的返回值。
around:环绕通知(应用:十分强大,可以做任何事情)
方法执行前后分别执行,可以阻止方法的执行
必须手动执行目标方法
afterThrowing:抛出异常通知(应用:包装异常信息)
方法抛出异常后执行,如果方法没有抛出异常,无法执行
after:最终通知(应用:清理现场)
方法执行完毕后执行,无论方法中是否出现异常
环绕
try{
//前置:before
//手动执行目标方法
//后置:afterRetruning
} catch(){
//抛出异常 afterThrowing
} finally{
//最终 after
}
基于xml:
编写切面类;
/
*

  • 切面类,含有多个通知*/

    public class MyAspect {

public void myBefore(JoinPoint joinPoint){
	System.out.println("前置通知 : " + joinPoint.getSignature().getName());
}

public void myAfterReturning(JoinPoint joinPoint,Object ret){
	System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
}

public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
	System.out.println("前");
	//手动执行目标方法
	Object obj = joinPoint.proceed();
	
	System.out.println("后");
	return obj;
}

public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
	System.out.println("抛出异常通知 : " + e.getMessage());
}

public void myAfter(JoinPoint joinPoint){
	System.out.println("最终通知");
   }
}

spring配置:

<!-- 1 创建目标类 -->
<bean id="userServiceId" class="com.itheima.d_aspect.a_xml.UserServiceImpl"></bean>
<!-- 2 创建切面类(通知) -->
<bean id="myAspectId" class="com.itheima.d_aspect.a_xml.MyAspect"></bean>
<!-- 3 aop编程 
	<aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)
		ref 切面类引用
	<aop:pointcut> 声明一个切入点,所有的通知都可以使用。
		expression 切入点表达式
		id 名称,用于其它通知引用
-->
<aop:config>
	<aop:aspect ref="myAspectId">
		<aop:pointcut expression="execution(* com.itheima.d_aspect.a_xml.UserServiceImpl.*(..))" id="myPointCut"/>
		
		<!-- 1 前置通知 
			<aop:before method="" pointcut="" pointcut-ref=""/>
				method : 通知,及方法名
				pointcut :切入点表达式,此表达式只能当前通知使用。
				pointcut-ref : 切入点引用,可以与其他通知共享切入点。
			通知方法格式:public void myBefore(JoinPoint joinPoint){
				参数1:org.aspectj.lang.JoinPoint  用于描述连接点(目标方法),获得目标方法名等
			例如:
		<aop:before method="myBefore" pointcut-ref="myPointCut"/>
		-->
		<!-- 2后置通知  ,目标方法后执行,获得返回值
			<aop:after-returning method="" pointcut-ref="" returning=""/>
				returning 通知方法第二个参数的名称
			通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){
				参数1:连接点描述
				参数2:类型Object,参数名 returning="ret" 配置的
			例如:
		<aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />
		-->
		
		<!-- 3 环绕通知 
			<aop:around method="" pointcut-ref=""/>
			通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
				返回值类型:Object
				方法名:任意
				参数:org.aspectj.lang.ProceedingJoinPoint
				抛出异常
			执行目标方法:Object obj = joinPoint.proceed();
			例如:
		<aop:around method="myAround" pointcut-ref="myPointCut"/>
		-->
		<!-- 4 抛出异常
			<aop:after-throwing method="" pointcut-ref="" throwing=""/>
				throwing :通知方法的第二个参数名称
			通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
				参数1:连接点描述对象
				参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置
			例如:
		<aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
		-->
		<!-- 5 最终通知 -->			
		<aop:after method="myAfter" pointcut-ref="myPointCut"/>
	</aop:aspect>
</aop:config>

基于注解 (注解需掌握):
注解首先要注意需要在spring中扫描
1:替换bean:
@Service(“userServicedId”)
pulic class UserServiceImp implements userService{
}
@Component
public class Myaspect{
2:替换aop
必须进行aspectj 自动代理

<!-- 2.确定 aop注解生效 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

声明切面
<aop:aspect ref=“myAspectId”>
上面的替换为
@component
@Aspect
public class Myaspect{

替换前置通知

<aop:before method="myBefore" pointcut="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))"/>

//切入点当前有效

@Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
public void myBefore(JoinPoint joinPoint){
	System.out.println("前置通知 : " + joinPoint.getSignature().getName());
}

替换 公共切入点

<aop:pointcut expression="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" id="myPointCut"/>

声明公共切入点

@Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
private void myPointCut(){
}

替换后置

  <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />

@AfterReturning(value="myPointCut()" ,returning="ret")
public void myAfterReturning(JoinPoint joinPoint,Object ret){
	System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
}

替换环绕

	<aop:around method="myAround" pointcut-ref="myPointCut"/>
	@Around(value = "myPointCut()")
public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
	System.out.println("前");
	//手动执行目标方法
	Object obj = joinPoint.proceed();
	
	System.out.println("后");
	return obj;
}

    替换抛出异常:

	<aop:after-throwing method="myAfterThrowing" pointcut="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" throwing="e"/>
	@AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")
public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
	System.out.println("抛出异常通知 : " + e.getMessage());
}

编写切面类:
切面类,含有多个通知

 @Component
 @Aspect
 public class MyAspect {
 //切入点当前有效
 //	@Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
public void myBefore(JoinPoint joinPoint){
	System.out.println("前置通知 : " + joinPoint.getSignature().getName());
}
//声明公共切入点
@Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
private void myPointCut(){
}
//	@AfterReturning(value="myPointCut()" ,returning="ret")
public void myAfterReturning(JoinPoint joinPoint,Object ret){
	System.out.println("后置通知 : " + joinPoint.getSignature().getName() + " , -->" + ret);
}
//	@Around(value = "myPointCut()")
public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
	System.out.println("前");
	//手动执行目标方法
	Object obj = joinPoint.proceed();
	
	System.out.println("后");
	return obj;
}
//	@AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")
public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
	System.out.println("抛出异常通知 : " + e.getMessage());
}
@After("myPointCut()")
public void myAfter(JoinPoint joinPoint){
	System.out.println("最终通知");
 }
 }

Spring 配置

<!-- 1.扫描 注解类 -->
<context:component-scan base-package="com.itheima.d_aspect.b_anno"></context:component-scan>
<!-- 2.确定 aop注解生效 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

最后关于Spring的总结,归根到底还是要了解了这个思想,当你明白了这个思想的时候,你会发现其实这个整体思路你就有了,就不会感到那么难,简而言之,多敲代码,多理思路,多总结。在下也是小菜鸡一个(博客的有些格式还不会,下次好好排版,瑟瑟发抖),这个也是根据学习视频的笔记写的,如果有什么不好的,希望提出,一起进步。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值