Spring AOP的基於AspectJ註解開發
阿新 • • 發佈:2019-01-03
一.Spring的AOP的註解開發詳細過程
1.編寫目標類並配置
這個目標類並沒有實現介面,因此spring會自動用Cglib來對其進行動態代理
public class OrderDao { void add(){ System.out.println("add..."); } void delete(){ System.out.println("delete..."); } void update(){ System.out.println("update..."); } void find(){ System.out.println("find..."); } }
<!--配置目標類-->
<bean id="OrderDao" class="org.qingyu.dao.OrderDao"></bean>
2.編寫切面類並配置
//切面類
public class MyAspect {
public void before(){
System.out.println("前置通知...");
}
}
<!--配置切面類--> <bean id="MyAspect" class="org.qingyu.aspect.MyAspect"></bean>
3.使用註解對目標類進行增強
//切面類
@Aspect
public class MyAspect {
@Before(value = "execution(* org.qingyu.dao.OrderDao.add(..))")
public void before(){
System.out.println("前置通知...");
}
}
4.編寫測試類
public static void main(String[] args){ ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml"); OrderDao orderDao = (OrderDao) applicationContext.getBean("OrderDao"); orderDao.add(); }
輸出結果如下:
前置通知...
add...
二.Spring的AOP的註解的通知型別
[email protected] 前置通知
@Before(value = "execution(* org.qingyu.dao.OrderDao.add(..))")
public void before(){
System.out.println("前置通知...");
}
[email protected] 後置通知
@AfterReturning(value = "execution(* org.qingyu.dao.OrderDao.delete(..))" ,returning = "result")
public void afterReturning(Object result){
System.out.println("後置通知..."+result);
}
[email protected] 環繞通知
@Around(value = "execution(* org.qingyu.dao.OrderDao.find(..))")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("環繞前...");
Object obj = proceedingJoinPoint.proceed();
System.out.println("環繞後...");
return obj;
}
[email protected] 異常丟擲通知
@AfterThrowing(value = "execution(* org.qingyu.dao.OrderDao.update(..))",throwing = "e")
public void afterThrowing(Throwable e){
System.out.println("異常丟擲通知..."+e.getMessage());
}
三.Spring的註解的AOP的切入點的配置
@After(value = "MyAspect.pointCut1()")
public void after(){
System.out.println("最終通知...");
}
@Pointcut(value = "execution(* org.qingyu.dao.OrderDao.update(..))")
private void pointCut1(){}