There are often some extensions to existing programs that you don't want to modify existing code. You can use the proxy method, commonly used agent technology has JDK Java.lang.reflect.Proxy, spring's agent and so on.
For example, the method plus transaction, the common Org.springframework.transaction.interceptor.TransactionInterceptor. He just opens the transaction in front of the existing method, and then closes the transaction.
This article takes SPRING+ASPECTJ as a simple example:
1. The files used by Maven depend on the following:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.4</version>
</dependency>
2. As an example, you need to execute a section of code before the specified method:
public class Boforeaspect {
public void before () {
System.out.println ("Before method do something ...");
}
}
3. Configure Spring
<bean id= "Testinterceptor" class= "Net.highersoft.spring.TestInterceptor"/>
<bean id= "Boforeaspect" class= "Net.highersoft.spring.BoforeAspect" ></bean>
<aop:config proxy-target-class= "true" >
<aop:aspect ref= "Boforeaspect" >
<aop:before method= "Before" pointcut= "Execution (* net.highersoft.spring.*.* (..))" />
</aop:aspect>
</aop:config>
4. Write the test program
public class Testinterceptor {
public static void Main (string[] args) {
ApplicationContext CTX = new Filesystemxmlapplicationcontext ("Classpath:test.xml");
Testinterceptor US = (testinterceptor) ctx.getbean ("Testinterceptor");
Us.printuser ("Chengzhong");
}
public void Printuser (String user) {
System.out.println ("Printuser User:" + user);
}
}
Ha, in total less than 50 lines of code, done.
50 Line Code implements Java method proxy