Spring基于@AspectJ AOP例子

Julywhj 2015-12-17

1.使用前准备

      Spring在修理@Aspect注解表达式时,需要将Spring的asm模块加到类路径中。asm是轻量级的字节码处理框架,因为java的反射机制无法获取入参名,Spring就利用asm处理@AspectJ中所描述的方法入参名。

      此外还需要加入aspectj.weaver和aspectj.tools类包。

2.配置使用@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:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
	<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

 3.通过注解对类的进行设置

 @Before

@After

@AfterReturning

@Around

@AfterThrowing

package com.baobaotao.aspectj.advanced;

import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class TestAspect {
	//-------------复合运算----------
//	@Before("!target(com.baobaotao.NaiveWaiter) "+
//			"&& execution(* serveTo(..)))")
//	public void notServeInNaiveWaiter() {
//		System.out.println("--notServeInNaiveWaiter() executed!--");
//	}
//	@After("within(com.baobaotao.*) "
//			+ " && execution(* greetTo(..)))")
//	public void greeToFun() {
//		System.out.println("--greeToFun() executed!--");
//	}
//	
//	@AfterReturning("target(com.baobaotao.Waiter) || "+
//			        " target(com.baobaotao.Seller)")
//	public void waiterOrSeller(){
//		System.out.println("--waiterOrSeller() executed!--");
//	}
	
//	//------------引用命名切点----------//
//	@Before("TestNamePointcut.inPkgGreetTo()")
//	public void pkgGreetTo(){
//		System.out.println("--pkgGreetTo() executed!--");
//	}
//
//	@Before("!target(com.baobaotao.NaiveWaiter) && "
//			+"TestNamePointcut.inPkgGreetTo()")
//	public void pkgGreetToNotNaiveWaiter(){
//		System.out.println("--pkgGreetToNotNaiveWaiter() executed!--");
//	}
//
    //------------访问连接点对象----------//
//	@Around("execution(* greetTo(..)) && target(com.baobaotao.NaiveWaiter)")
//	public void joinPointAccess(ProceedingJoinPoint pjp) throws Throwable{
//		System.out.println("------joinPointAccess-------");
//		System.out.println("args[0]:"+pjp.getArgs()[0]);		
//		System.out.println("signature:"+pjp.getTarget().getClass());
//		pjp.proceed();
//		System.out.println("-------joinPointAccess-------");
//	}
	
  //------------绑定连接点参数----------//
//	@Before("target(com.baobaotao.NaiveWaiter) && args(name,num,..)")
//	public void bindJoinPointParams(int num,String name){
//	   System.out.println("----bindJoinPointParams()----");
//	   System.out.println("name:"+name);
//	   System.out.println("num:"+num);
//	   System.out.println("----bindJoinPointParams()----");
//	}

  //------------绑定代理对象----------//
//	@Before("execution(* greetTo(..)) && this(waiter)")
//	@Before("this(waiter)")
//	public void bindProxyObj(Waiter waiter){
//	   System.out.println("----bindProxyObj()----");
//	   System.out.println(waiter.getClass().getName());
//	   System.out.println("----bindProxyObj()----");
//	}
	
	  //------------绑定类标注对象----------//
//	@Before("@within(m)")
//	public void bindTypeAnnoObject(Monitorable m){
//	   System.out.println("----bindTypeAnnoObject()----");
//	   System.out.println(m.getClass().getName());
//	   System.out.println("----bindTypeAnnoObject()----");
//	}
    //------------绑定抛出的异常----------//
//	@AfterReturning(value="target(com.baobaotao.SmartSeller)",returning="retVal")
//	public void bingReturnValue(int retVal){
//	   System.out.println("----bingReturnValue()----");
//	   System.out.println("returnValue:"+retVal);
//	   System.out.println("----bingReturnValue()----");
//	}
	
//    //------------绑定抛出的异常----------//
	@AfterThrowing(value="target(com.baobaotao.SmartSeller)",throwing="iae")
	public void bindException(IllegalArgumentException iae){
	   System.out.println("----bindException()----");
	   System.out.println("exception:"+iae.getMessage());
	   System.out.println("----bindException()----");
	}	

}

其中相关的类

public interface Waiter {
	@NeedTest
	public void greetTo(String clientName);	
	public void serveTo(String clientName);
}


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Monitorable {

}



@Monitorable
public class NaiveWaiter implements Waiter {
	@NeedTest
	public void greetTo(String clientName) {
		System.out.println("NaiveWaiter:greet to "+clientName+"...");
	}	
	@NeedTest
	public void serveTo(String clientName){
		System.out.println("NaiveWaiter:serving "+clientName+"...");
	}
	public void smile(String clientName,int times){
		System.out.println("NaiveWaiter:smile to  "+clientName+ times+"times...");
	}	
}


public class NaughtyWaiter implements Waiter {
	public void greetTo(String clientName) {
		System.out.println("NaughtyWaiter:greet to "+clientName+"...");
	}	
	public void serveTo(String clientName){
		System.out.println("NaughtyWaiter:serving "+clientName+"...");
	}
	public void joke(String clientName,int times){
        	System.out.println("NaughtyWaiter:play "+times+" jokes to "+clientName+"...");
	}
}


public interface Seller {
  int sell(String goods,String clientName);
}
public class SmartSeller implements Seller {

	public int sell(String goods,String clientName) {
		System.out.println("SmartSeller: sell "+goods +" to "+clientName+"...");
		return 100;
	}
	
	public void checkBill(int billId){
		if(billId == 1) throw new IllegalArgumentException("iae Exception");
		else throw new RuntimeException("re Exception");
	}
}



public class TestNamePointcut {
	@Pointcut("within(com.baobaotao.*)")
	private void inPackage(){}
	
	@Pointcut("execution(* greetTo(..)))")
    protected void greetTo(){}

    @Pointcut("inPackage() and greetTo()")
    public void inPkgGreetTo(){}
}

3.测试例子

package com.baobaotao.aspectj.advanced;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.baobaotao.SmartSeller;
import com.baobaotao.Waiter;

public class AdvancedTest {
	public static void main(String[] args) {
		String configPath = "com/baobaotao/aspectj/advanced/beans.xml";
		ApplicationContext ctx = new ClassPathXmlApplicationContext(configPath);
		Waiter naiveWaiter = (Waiter) ctx.getBean("naiveWaiter");
		//NaiveWaiter naiveWaiter1 = (NaiveWaiter) ctx.getBean("naiveWaiter");
		Waiter naughtyWaiter = (Waiter) ctx.getBean("naughtyWaiter");
//		naiveWaiter.greetTo("John");
//		naiveWaiter.serveTo("John");
//		naughtyWaiter.greetTo("Tom");
//		naughtyWaiter.serveTo("Tom");
		
        //--通过joinPoint接口访问连接点上下文信息
//		naiveWaiter.greetTo("John");
		
		//--绑定连接点参数
		//((NaiveWaiter)naiveWaiter).smile("John",2);
		//naiveWaiter1.smile("John",2);
		
		//--绑定代理对象
//		naiveWaiter.greetTo("John");
		
		//--绑定类注解
//		((NaiveWaiter)naiveWaiter).greetTo("John");

		//绑定返回值
//		SmartSeller seller = (SmartSeller) ctx.getBean("seller");
//		seller.sell("Beer","John");	
		
		//绑定异常
		SmartSeller seller = (SmartSeller) ctx.getBean("seller");
		seller.checkBill(2);
		//seller.checkBill(1);
	}
}

相关推荐