[转]Spring 各种Advice示例

直接上代码

[java] view plaincopyprint?

  1. package com.dada.test.spring.aop.advisor;  

  2.   

  3. import java.lang.reflect.Method;  

  4. import org.springframework.aop.AfterReturningAdvice;  

  5.    

  6. public class MyAfterAdvice implements AfterReturningAdvice  

  7. {  

  8.   

  9.     public void afterReturning(Object result, Method method,  

  10.             Object[] parameter, Object target) throws Throwable {  

  11.         System.out.println("==============after return==============");  

  12.         System.out.println("result:" + result + ";method:" + method  

  13.                 + ";parameter:" + parameter + ";target:" + target);  

  14.     }  

  15.   

  16. }  

package com.dada.test.spring.aop.advisor;

import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
 
public class MyAfterAdvice implements AfterReturningAdvice
{

	public void afterReturning(Object result, Method method,
			Object[] parameter, Object target) throws Throwable {
		System.out.println("==============after return==============");
		System.out.println("result:" + result + ";method:" + method
				+ ";parameter:" + parameter + ";target:" + target);
	}

}


 

[java] view plaincopyprint?

  1. package com.dada.test.spring.aop.advisor;  

  2.   

  3. import java.util.HashSet;  

  4. import java.util.Set;  

  5. import org.aopalliance.intercept.MethodInterceptor;  

  6. import org.aopalliance.intercept.MethodInvocation;  

  7.    

  8. public class MyAroundAdvice implements MethodInterceptor  

  9. {  

  10.     private Set set=new HashSet();  

  11.     public Object invoke(MethodInvocation method) throws Throwable  

  12.     {  

  13.         set.add(method);  

  14.         System.out.println("============around before==========");  

  15.         Object result=method.proceed();  

  16.         System.out.println("============around after==========");  

  17.         return result;  

  18.     }  

  19. }  

package com.dada.test.spring.aop.advisor;

import java.util.HashSet;
import java.util.Set;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
 
public class MyAroundAdvice implements MethodInterceptor
{
    private Set set=new HashSet();
    public Object invoke(MethodInvocation method) throws Throwable
    {
        set.add(method);
        System.out.println("============around before==========");
        Object result=method.proceed();
        System.out.println("============around after==========");
        return result;
    }
}


 

[java] view plaincopyprint?

  1. package com.dada.test.spring.aop.advisor;  

  2.   

  3. import java.lang.reflect.Method;  

  4. import org.springframework.aop.MethodBeforeAdvice;  

  5.    

  6. public class MyBeforeAdvice implements MethodBeforeAdvice  

  7. {  

  8.      

  9.     public void before(Method method, Object[] parameters, Object target) throws Throwable  

  10.     {  

  11.         System.err.println("==========before===========");  

  12.         System.out.println(method.getName());  

  13.         System.out.println(parameters.length);  

  14.         System.out.println(target);  

  15.     }  

  16. }  

package com.dada.test.spring.aop.advisor;

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
 
public class MyBeforeAdvice implements MethodBeforeAdvice
{
   
    public void before(Method method, Object[] parameters, Object target) throws Throwable
    {
        System.err.println("==========before===========");
        System.out.println(method.getName());
        System.out.println(parameters.length);
        System.out.println(target);
    }
}


 

[java] view plaincopyprint?

  1. package com.dada.test.spring.aop.advisor;  

  2.   

  3. import org.springframework.aop.ThrowsAdvice;  

  4. import com.dada.test.spring.aop.MyException;  

  5.   

  6. public class MyThrowsAdvice implements ThrowsAdvice  

  7. {  

  8.     public void afterThrowing(MyException e)  

  9.     { // 可以定义多个方法,只要传入的参数是不同异常   

  10.         System.err.println("MyThrowsAdvice:"+e.toString());  

  11.     }  

  12.    

  13.     public void afterThrowing(RuntimeException e)  

  14.     {  

  15.         // 可以定义多个方法,只要传入的参数是不同异常   

  16.         System.err.print("RuntimeException!");  

  17.     }  

  18. }  

package com.dada.test.spring.aop.advisor;

import org.springframework.aop.ThrowsAdvice;
import com.dada.test.spring.aop.MyException;

public class MyThrowsAdvice implements ThrowsAdvice
{
    public void afterThrowing(MyException e)
    { // 可以定义多个方法,只要传入的参数是不同异常
        System.err.println("MyThrowsAdvice:"+e.toString());
    }
 
    public void afterThrowing(RuntimeException e)
    {
        // 可以定义多个方法,只要传入的参数是不同异常
        System.err.print("RuntimeException!");
    }
}


 

[java] view plaincopyprint?

  1. package com.dada.test.spring.aop.service;  

  2.   

  3. public interface IService {  

  4.   

  5.     String doSth();  

  6.       void doA();  

  7. }  

package com.dada.test.spring.aop.service;

public interface IService {

	String doSth();
	  void doA();
}


 

[java] view plaincopyprint?

  1. package com.dada.test.spring.aop.service;  

  2.   

  3. import com.dada.test.spring.aop.MyException;  

  4.   

  5. public class MyServiceImpl implements IService{  

  6.   

  7.      public String doSth()  

  8.       {  

  9.         System.out.println(this);  

  10.         System.out.println("MyServiceImpl doSth");  

  11.         return "cindy";  

  12.       }  

  13.   

  14.      public void doA()  

  15.       {  

  16.         System.out.println("MyServiceImpl doA");  

  17.         throw new MyException("111111111");  

  18.       }  

  19.   

  20. }  

package com.dada.test.spring.aop.service;

import com.dada.test.spring.aop.MyException;

public class MyServiceImpl implements IService{

	 public String doSth()
	  {
	    System.out.println(this);
	    System.out.println("MyServiceImpl doSth");
	    return "cindy";
	  }

	 public void doA()
	  {
		System.out.println("MyServiceImpl doA");
	    throw new MyException("111111111");
	  }

}


 

[html] view plaincopyprint?

  1. <?xml version="1.0" encoding="UTF-8"?>  

  2. <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">  

  3. <beans default-lazy-init="true">  

  4.     <bean name="beforeAdvice" class="com.dada.test.spring.aop.advisor.MyBeforeAdvice" />  

  5.     <bean name="aroundAdvice" class="com.dada.test.spring.aop.advisor.MyAroundAdvice" />  

  6.     <bean name="afterAdvice" class="com.dada.test.spring.aop.advisor.MyAfterAdvice" />  

  7.     <bean name="throwsAdvice" class="com.dada.test.spring.aop.advisor.MyThrowsAdvice" />  

  8.     <bean id="servTarget" class="com.dada.test.spring.aop.service.MyServiceImpl" />  

  9.     <bean id="invoker"  

  10.         class="org.springframework.aop.framework.ProxyFactoryBean">  

  11.         <property name="proxyInterfaces" value="com.dada.test.spring.aop.service.IService" />  

  12.         <property name="target" ref="servTarget" />  

  13.         <property name="singleton" value="false" />  

  14.         <property name="interceptorNames">  

  15.           <list>  

  16.             <value>beforeAdvice</value>  

  17.             <value>aroundAdvice</value>  

  18.             <value>afterAdvice</value>  

  19.             <value>afterAdvice</value>  

  20.             <value>throwsAdvice</value>  

  21.         </list>  

  22.         </property>  

  23.     </bean>  

  24. </beans>  

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans default-lazy-init="true">
    <bean name="beforeAdvice" class="com.dada.test.spring.aop.advisor.MyBeforeAdvice" />
    <bean name="aroundAdvice" class="com.dada.test.spring.aop.advisor.MyAroundAdvice" />
    <bean name="afterAdvice" class="com.dada.test.spring.aop.advisor.MyAfterAdvice" />
    <bean name="throwsAdvice" class="com.dada.test.spring.aop.advisor.MyThrowsAdvice" />
    <bean id="servTarget" class="com.dada.test.spring.aop.service.MyServiceImpl" />
    <bean id="invoker"
        class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="proxyInterfaces" value="com.dada.test.spring.aop.service.IService" />
        <property name="target" ref="servTarget" />
        <property name="singleton" value="false" />
        <property name="interceptorNames">
          <list>
            <value>beforeAdvice</value>
            <value>aroundAdvice</value>
            <value>afterAdvice</value>
            <value>afterAdvice</value>
            <value>throwsAdvice</value>
        </list>
        </property>
    </bean>
</beans>


 

[java] view plaincopyprint?

  1. package com.dada.test.spring.aop;  

  2.   

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

  4.   

  5. import com.dada.test.spring.aop.service.IService;  

  6.   

  7. public class TestSpringAop {  

  8.   

  9. public static void main(String[] args) throws Exception  

  10. {  

  11.     ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]  

  12.     {  

  13.         "com/dada/test/spring/aop/aop-context.xml"  

  14.     });  

  15.     IService ser = (IService) ctx.getBean("invoker");  

  16.     String rs = ser.doSth();  

  17.     System.out.println("rs="+rs.toString());  

  18.      

  19.     try  

  20.     {  

  21.         ser.doA();  

  22.     }  

  23.     catch (Throwable t)  

  24.     {  

  25.         t.printStackTrace();  

  26.     }  

  27.       

  28. }  

  29.   

  30. }  

package com.dada.test.spring.aop;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.dada.test.spring.aop.service.IService;

public class TestSpringAop {

public static void main(String[] args) throws Exception
{
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]
    {
        "com/dada/test/spring/aop/aop-context.xml"
    });
    IService ser = (IService) ctx.getBean("invoker");
    String rs = ser.doSth();
    System.out.println("rs="+rs.toString());
   
    try
    {
        ser.doA();
    }
    catch (Throwable t)
    {
        t.printStackTrace();
    }
    
}

}


运行结果如下:

2013-7-18 23:21:06 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@14ed9ff: display name [org.springframework.context.support.ClassPathXmlApplicationContext@14ed9ff]; startup date [Thu Jul 18 23:21:06 CST 2013]; root of context hierarchy
2013-7-18 23:21:06 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [com/dada/test/spring/aop/aop-context.xml]
2013-7-18 23:21:07 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@14ed9ff]: org.springframework.beans.factory.support.DefaultListableBeanFactory@12152e6
2013-7-18 23:21:07 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@12152e6: defining beans [beforeAdvice,aroundAdvice,afterAdvice,throwsAdvice,servTarget,invoker]; root of factory hierarchy
2013-7-18 23:21:07 org.springframework.aop.framework.ProxyFactoryBean getObject
警告: Using non-singleton proxies with singleton targets is often undesirable.Enable prototype proxies by setting the 'targetName' property.
==========before===========
doSth
0
com.dada.test.spring.aop.service.MyServiceImpl@6f7ce9
============around before==========
com.dada.test.spring.aop.service.MyServiceImpl@6f7ce9
MyServiceImpl doSth
==============after return==============
result:cindy;method:public abstract java.lang.String com.dada.test.spring.aop.service.IService.doSth();parameter:[Ljava.lang.Object;@1dfafd1;target:com.dada.test.spring.aop.service.MyServiceImpl@6f7ce9
==============after return==============
result:cindy;method:public abstract java.lang.String com.dada.test.spring.aop.service.IService.doSth();parameter:[Ljava.lang.Object;@8fce95;target:com.dada.test.spring.aop.service.MyServiceImpl@6f7ce9
============around after==========
rs=cindy
==========before===========
doA
0
com.dada.test.spring.aop.service.MyServiceImpl@6f7ce9
============around before==========
MyServiceImpl doA
MyThrowsAdvice:com.dada.test.spring.aop.MyException: 111111111
com.dada.test.spring.aop.MyException: 111111111
 at com.dada.test.spring.aop.service.MyServiceImpl.doA(MyServiceImpl.java:17)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:585)
 at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:304)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
 at org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor.invoke(ThrowsAdviceInterceptor.java:126)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
 at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:50)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
 at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:50)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
 at com.dada.test.spring.aop.advisor.MyAroundAdvice.invoke(MyAroundAdvice.java:15)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
 at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:50)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
 at $Proxy0.doA(Unknown Source)
 at com.dada.test.spring.aop.TestSpringAop.main(TestSpringAop.java:21)

after return出现了2次请注意,思考下是什么原因

你可能感兴趣的:(spring)