The previous note describes the agent mechanism, which describes how spring implements the proxy.
An example to illustrate.
Package download Address (two):
Http://www.blogjava.net/Files/ducklyl/springaop.rar
Http://www.blogjava.net/Files/ducklyl/Spring.rar
(1) Creating the Logbeforeadvice class (Implementing the Methodbeforeadvice interface, which is called before the method of the target object is executed)package com.proxy;
import java.lang.reflect.*;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.springframework.aop.MethodBeforeAdvice;;
public class LogBeforeAdvice implements MethodBeforeAdvice{
private Logger logger=Logger.getLogger(this.getClass().getName());
public void before(Method method,Object[] args,Object target) throws Throwable
{
logger.log(Level.INFO,"mehtod starts "+method);
}
}
(2) Create configuration file Advice-config.xml <?xml version= "1.0" encoding= "UTF-8"
<! DOCTYPE beans Public "-//spring//dtd bean//en" "Http://www.springframework.org/dtd/spring-beans.dtd"
< Beans>
<bean id= "Logbeforeadvice" class= "Com.proxy.LogBeforeAdvice"/>
<bean id= "Hellospeaker" class= "Com.proxy.HelloSpeaker"/>
<bean id= "Helloproxy"
class= " Org.springframework.aop.framework.ProxyFactoryBean "><!--set up proxy objects;
<property name=" Proxyinterfaces "><!--agent interface;
<value>com.proxy.ihello</value>
</property>
<property name= "target" ><!--proxy target;
<ref bean= "Hellospeaker"/>
</property>
< Property Name= "Interceptornames" ><!--Proxy implementation class;
<list>
<value>logbeforeadvice</ Value>
</list>
</property>
</bean>
</beans>
(3) test class Springaopdemo
Package com.proxy;
Import Org.springframework.contexT.applicationcontext;
Import Org.springframework.context.support.FileSystemXmlApplicationContext;
public class Springaopdemo {
public static void Main (string[] args)
{
//Read config file
ApplicationContext Co Ntext=new filesystemxmlapplicationcontext ("Advice-config.xml");
Ihello helloproxy= (Ihello) Context.getbean ("Helloproxy");
Helloproxy.hello ("ducklyl");
}
}
Run the test class with the following results:
Hello,ducklyl