Spring中AOP使用——配置xml方式

1.確認目標(bean)

<!-- 目標target -->
<bean id="customerService" class="cn.itcast.spring.a_proxy.CustomerServiceImpl"></bean>
<bean id="productService" class="cn.itcast.spring.a_proxy.ProductService"></bean>

2.編寫通知(通知實現一個接口)

<!-- 通知加強advice -->
<bean id="myAspect" class="cn.itcast.spring.c_aopaspectj.MyAspect"></bean>

通知方法

前置通知java

public void before(JoinPoint joinPoint){
	//判斷某用戶可執行的方法中,是否存在要運行的方法
	if("method1".equals(joinPoint.getSignature().getName())){
		throw new RuntimeException("沒有權限執行該方法");
	}
}

後置通知spring

public void afterReturing(JoinPoint joinPoint, Object returnVal){
	//加強
}

環繞通知express

public Object around(ProceedingJoinPoint proceedJoinPoint) throws Throwable{
	//目標方法的執行
	Object object = proceedJoinPoint.proceed();
	return object;	
}

環繞通知-終極版app

public Object around(ProceedingJoinPoint proceedingJoinPoint){
	try{
		//前置通知
		Object result = proceedingJoinPoint.proceed();
		//後置通知
	}catch(Exception e){
		//拋出通知
	}finally{
		//最終通知
		return Object
	}
}

拋出通知代理

public void afterThrowing(JoinPoint joinPoint, Throwable ex){
	System.out.println(joinPoint.getTarget().getClass().getSimpleName()+" : "+joinPoint.getSignature().getName()+"  : "+ex.getMessage());
}

最終通知code

public void after(JoinPoint joinPoint){
	System.out.println(joinPoint.toLongString());
}

##3. 配置切點切面 ##xml

applicationContext-aspectj.xml對象

<!-- 配置切入點和切面 -->
<aop:config>
	<!-- 切面 -->
	<aop:aspect ref="myAspect">
		<!-- 切入點 -->
		<aop:pointcut expression="within(cn.itcast.spring..*)" id="myPointcut" />
		<!-- 前置通知 -->
		<aop:before method="before" pointcut-ref="myPointcut" />
		<!-- 後置通知 -->
		<aop:after-returning method="afterReturning" pointcut-ref="myPointcut" returning="returnVal" /> 
		<!-- 環繞通知 -->
		<aop:around method="around" pointcut-ref="myPointcut"/>
		<!-- 拋出通知 -->
		<aop:after-throwing method="afterThrowing" pointcut-ref="myPointcut" throwing="ex" />
		<!-- 最終通知 -->
		<aop:after method="after" pointcut-ref="myPointcut"/>	
	</aop:aspect>
</aop:config>

切入點可直接寫入通知中接口

<aop:before method="before" pointcut="bean(*Service)" />

異常

java.lang.ClassCastException:com.sun.proxy.$Proxy17 cannot be cast to xxxServiceImpl

緣由:使用了jdk動態代理,目標對象是接口,沒法轉換爲子類get

解決方法: 使用類代理(cglib動態代理)

註解:

<aop:aspect-autoproxy proxy-target-class="true" />

xml

<aop:config proxy-target-class="true">
相關文章
相關標籤/搜索