工作中经常需要对现有程序进行一些扩展,而不想修改现有代码。可以使用代理方法,常使用的代理技术有JDK的java.lang.reflect.Proxy、spring的代理等.

例如对方法加事务,就常用org.springframework.transaction.interceptor.TransactionInterceptor。他就是在现有方法前面开启事务,后面关闭事务。

本文以spring+aspectj做一个简单的例子:
1.使用maven依赖的文件如下:
        <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.以需要在指定方法前面执行一段代码为例:
public class BoforeAspect {
    public void before(){
        System.out.println("before method do something....");
    }
}
3.配置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.写测试程序
public class TestInterceptor {
    public static void main(String[] args) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext("classpath:test.xml");
        TestInterceptor us = (TestInterceptor) ctx.getBean("testInterceptor");
        us.printUser("程忠");
    }
    public void printUser(String user) {
        System.out.println("printUser user:" + user);
    }
}
哈,总共不到50行代码,搞定。