pringframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
beforeMethodBean
afterMethodBean
throwException
执行结果如下:
[plain]
三月 20, 2013 2:37:36 下午 org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@eb67e8: startup date [Wed Mar 20 14:37:36 CST 2013]; root of context hierarchy
三月 20, 2013 2:37:36 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [resource/aop.xml]
三月 20, 2013 2:37:36 下午 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@157985: defining beans [book,beforeMethodBean,afterMethodBean,throwException,bookProxy]; root of factory hierarchy
---------------------
Before Method
--------------------
Book name Effective java
-------------------
After method
---------------------
Before Method
--------------------
Book URL www.google.cn
-------------------
After method
----------------------
Before Method
--------------------
after Throwing Exception
4:Around advice
这个advice 联合了上面的三个advices,在方法执行期间执行,创建一个类实现MethodInterceptor接口,需要在方法中执行Object result = methodInvocation.proceed();方法才能得到执行,否则方法不会执行。
类如下:
[java]
package com.myapp.core.aop.advice;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class AroundMethod implements MethodInterceptor{
@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
// TODO Auto-generated method stub
System.out.println("method name:" + methodInvocation.getMethod().getName());
System.out.println("method arguments" + Arrays.toString(methodInvocation.getArguments()));
System.out.println("Around method : before ");
try{
Object result = methodInvocation.proceed();
System.out.println("Around method : after ");
return result;
}catch(IllegalArgumentException e){
System.out.println("Around method : throw an exception ");
throw e;
}
}
}
配置文件如下:
[html]
< xml version="1.0" encoding="UTF-8" >
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">