一、定义普通service类

package cn.edu.tju.service;


public class MyService {

public void method1() {
System.out.println("I am method 1");
}

public void method2() {
System.out.println("I am method 2");
}

public void method3() {
System.out.println("I am method 3");
}
}

二、创建java 配置类,并在其中创建ProxyFactoryBean,供

package cn.edu.tju.config;


import cn.edu.tju.service.MyService;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import java.lang.reflect.Method;

@Configuration
public class MyConfig {
@Bean
public MyService myService() {
return new MyService();
}

//MethodBeforeAdvice
@Bean
public MethodBeforeAdvice beforeAdvice() {
MethodBeforeAdvice advice = new MethodBeforeAdvice() {

@Override
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println("will call :"+ method);
System.out.println("args are: "+args);
}
};
return advice;
}



//MethodInterceptor
@Bean
public MethodInterceptor methodInterceptor() {
MethodInterceptor methodInterceptor = new MethodInterceptor() {
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
long starTime = System.nanoTime();
Object re = invocation.proceed();
long endTime = System.nanoTime();
System.out.println(invocation.getMethod() + " :" + (endTime - starTime));
return re;
}
};
return methodInterceptor;
}

//ProxyFactoryBean
@Bean
public ProxyFactoryBean proxyFactoryBean() {
ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
proxyFactoryBean.setTargetName("myService");
proxyFactoryBean.setInterceptorNames("beforeAdvice", "methodInterceptor");
return proxyFactoryBean;
}
}

三、创建容器,使用ProxyFactoryBean

package cn.edu.tju;

import cn.edu.tju.config.MyConfig;
import cn.edu.tju.service.MyService;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class TestProxyFactoryBean {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
MyService bean = context.getBean("proxyFactoryBean", MyService.class);
System.out.println("--------------------------------------------");
bean.method1();
System.out.println("--------------------------------------------");
bean.method2();
System.out.println("--------------------------------------------");
bean.method3();
}
}