spring AOP切面開發 基於aspectJ框架切點的註解開發


spring AOP切面開發 基於aspectJ框架切點的註解開發


基於annotation方案,註解開發

第一步:在配置文件中開啓aspectj的註解

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

 

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


<!-- 過濾可以使用註解的對象的類 -->
<context:component-scan base-package="cmo.demo"></context:component-scan>

<!-- 開啓aspectj註解自動代理 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>

</beans>
 



第二步:

A,在通知類中用@component標籤來聲明一個通知

B,在通知類中用@Aspect來聲明一個切面

C,在通知類的方法中設置要過濾後,增強的方法

@Pointcut("execution(* *Test(..))")

public void pointcutTest(){};

D,在通知類中用標籤來設置環繞通知,前置通知等

@Before("pointcutTest()")

package cmo.demo.aspectj_annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

//用註解聲明是一個通知
@Component
@Aspect    //聲明這個類就是一個切面
public class CustomerServiceHelper {
	
	@Pointcut("execution(* *Test(..))")
	public void pointcutTest(){};
	
	
	@Before("pointcutTest()")
	public void before(JoinPoint jp) {
		System.out.println("前置通知...");
	}
	
	@AfterReturning("pointcutTest()")
	public void afterReturing(JoinPoint jp){
		System.out.println("後置通知");
	}
	
	@Around("pointcutTest()")
	public void around(ProceedingJoinPoint pjp) throws Throwable{
		System.out.println("環繞方法+方法前");
		
		Object proceed = pjp.proceed();
		
		System.out.println("環繞方法+方法後");
	}
	
	@AfterThrowing(value="pointcutTest()",throwing="ex")
	public void throwtest(JoinPoint jp, Throwable ex){
		System.out.println("我要拋異常了"+ex);
	}
	
	
	@After("pointcutTest()")
	public void after(JoinPoint jp){
		System.out.println("最終會執行的方法");

	}

}







將配置文件和通知類寫完以後就可以實現以上功能了





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章