Spring中AOP使用——註解方式

1.確認目標(bean)

業務層實現類java

@Service("xxxService")

注入對象spring

@Autowired

註解掃描.net

<context:component-scan base-package="cn.itcast" />

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

通知類上代理

[@Aspect](https://my.oschina.net/aspect)
@Component("myAspect")//將通知類交給spring管理

開啓Aspectj註解自動代理機制code

<aop:aspectj-autoproxy />

通知方法

前置通知component

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

後置通知xml

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

環繞通知對象

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

環繞通知-終極版接口

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

最終通知

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

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

通知方法上

@Before("value="execution(* cn.itcast.spring..*.*(..))")
@AfterReturning("value="execution(* cn.itcast.spring..*.*(..))")
@Around("value="execution(* cn.itcast.spring..*.*(..))")
@AfterThrowing("value="execution(* cn.itcast.spring..*.*(..))")
@After("value="execution(* cn.itcast.spring..*.*(..))")
@DeclareParents//引介通知

問題:若是直接在通知註解中寫切入點表達式,會發生重複編寫,後期不便於維護

解決:

在實際開發中,切入點都是單獨定義維護的,如:

1.使用xml定義切入點aop:pointcut

2.使用註解單獨定義切入點@Pointcut

@Pointcut("value="execution(* cn.itcast.spring..*.*(..))")
private void myPointcut(){
}

@Before(value="myPointcut()")

異常

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

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

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

註解:

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

xml

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