Spring AspectJ 框架配置详情

Aspect J 是一个基于Java语言的AOP框架

使用Aspect J需要导入Spring AOP 和 Aspect J的相关jar包

Spring AspectJ 框架配置详情_第1张图片

工程结构:

相关类:

StudentServiceI.java

package com.baidu.beans2;

public interface StudentServiceI {
	
	void delete();
	
	String add();

}

StudentServiceImpl.java

package com.baidu.beans2;

public class StudentServiceImpl implements StudentServiceI{

	@Override
	public void delete() {
		// TODO Auto-generated method stub
		System.out.println("delete student...");
	}

	@Override
	public String add() {
		// TODO Auto-generated method stub
		System.out.println("add student...");
		return "add";
	}

} 

Aspect J的几种增强:

@Before 前置通知,相当于BeforeAdvice
@AfterReturning 后置通知,相当于AfterReturningAdvice
@Around 环绕通知,相当于MethodInterceptor
@AfterThrowing抛出通知,相当于ThrowAdvice
@After 最终final通知,不管是否异常,该通知都会执行
@DeclareParents 引介通知,相当于IntroductionInterceptor

方式一:MyAspectJ.java

package com.baidu.beans2;

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.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyAspect {

	@Before(value="execution(* com.baidu.beans2..*(..))")
	public void myBefore(JoinPoint joinPoint) {
		System.out.println("前置增强。。。"+joinPoint);
		
	}
	@AfterReturning(value="execution(* com.baidu.beans2..*(..))",returning="reval")
	public void myAfterReturning(JoinPoint joinPoint,Object reval) {
		System.out.println("后置增强!!!,返回值"+reval);
		
	}
	@Around(value="execution(* com.baidu.beans2..*(..))")
	public void myAround(ProceedingJoinPoint joinPoint) throws Throwable {
		System.out.println("1.环绕增强前");
		Object res = joinPoint.proceed();
		System.out.println("2.环绕增强后"+res);
	}
}

方式二:MyAspectJ.java

package com.baidu.beans2;

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.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyAspect {
	@After(value = "MyAspect.zz()")
	public void myAfter() {
		System.out.println("最终通知。。。。");
	}
	@Pointcut(value="execution(* com.baidu.beans2..*(..))")
	public void zz() {		
	}
}

配置beans3.xml:



		
	
        	
	
        
         


execution表达式:

Spring AspectJ 框架配置详情_第2张图片

你可能感兴趣的:(spring)