被代理对象(目标对象)MyService:
package com.example.service;
public class MyService {
public String doFirst()
{
System.out.println("doFirst");
return "firstResult";
}
public String doLast()
{
System.out.println("doLast");
return "lastResult";
}
}
创建类MyMethodInterceptor实现cglib下的MethodInterceptor接口:
package com.example.proxy;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
public class MyMethodInterceptor implements MethodInterceptor {
private Object target;
public MyMethodInterceptor() {
super();
}
public MyMethodInterceptor(Object target) {
super();
this.target = target;
}
@Override
public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object result = null;
result = method.invoke(target, args);
System.out.println("添加增强效果");
if(result instanceof String){
result += "增强了";
}
return result;
}
}
定义工具类创建代理对象:
package com.example.proxy;
import com.example.service.MyService;
import net.sf.cglib.proxy.Enhancer;
public class FactoryProxy {
public Object createProxy(Object target)
{
//使用cglib创建代理对象
//1.创建cglib中的关键对象Enhancer
Enhancer en = new Enhancer();
//2.指定目标类
en.setSuperclass(target.getClass());
//3.指定增强功能的对象
en.setCallback(new MyMethodInterceptor(target));
//4.创建代理对象
return en.create();
}
}
测试代码:
package com.example.test;
import com.example.proxy.FactoryProxy;
import com.example.service.MyService;
public class CglibTest {
public static void main(String[] args) {
//1.创建目标对象
MyService target = new MyService();
//2.创建工具类
FactoryProxy factory = new FactoryProxy();
//3.调用工具方法,得到代理对象
MyService proxy = (MyService)factory.createProxy(target);
//4.通过代理对象,执行业务方法
String result = proxy.doFirst();
System.out.println(result);
}
}
效果:
doFirst
添加增强效果
firstResult增强了
|