SpringAop註解實現

該簡單例子實現方法的前置增強打印日誌,簡單的來說就是在調用某個方法之前會調用另一個方法

普通類:

Calculator

@Component
public class Calculator {
	public int add(int i,int j){
		return i+j;
	}
	public int sub(int i,int j){
		return i-j;
	}
	public int mul(int i,int j){
		return i*j;
	}
	public int div(int i,int j){
		return i/j;
	}
}
通過@Component註解將該類添加到IOC容器,在IOC容器中可以通過getBean("calculator")獲得實例

切面:

LoggingAspect

@Aspect
@Component
public class LoggingAspect {
	
	@Before("execution(public int springAop.Calculator.*(..))")
	public void beforMethod(JoinPoint joinPoint){
		String methodName=joinPoint.getSignature().getName();
		List<Object> s=Arrays.asList(joinPoint.getArgs());
		System.out.println(methodName+"方法開始之前,它的參數:"+s);
	}
}
指定了Calculator類中的所有發放都有個beforMethod()前置方法

@Aspect;@Before;JoinPoint;都是org.aspectj.lang包下的

@Aspect註解指定了該類爲切面

execution(public int springAop.Calculator.*(..))可以換爲execution(* springAop.Calculator.add(int,int))表明匹配返回值和修飾符爲任意類型的add(int ,int )方法



配置文件:

	<context:component-scan base-package="springAop"></context:component-scan>
	<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
有了第一行才能使用註解,有了第二行才能使用AOP


測試方法和結果:

	public static void main(String[] args) {
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		Calculator c=(Calculator) ctx.getBean("calculator");
		int a=c.add(3, 4);
		System.out.println("執行方法後的結果:"+a);
		a=c.div(6, 2);
		System.out.println("執行方法後的結果:"+a);
	}




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