动态代理--cglib 回调

来源:互联网 发布:国内数据库现状 编辑:程序博客网 时间:2024/05/19 17:26
package com.gqc.factory;import java.lang.reflect.Method;import net.sf.cglib.proxy.Enhancer;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.MethodProxy;import com.gqc.service.ISomeService;import com.gqc.service.SomeServiceImpl;public class MyCglibFactory implements MethodInterceptor {private ISomeService target;public MyCglibFactory() {target = new SomeServiceImpl();}public ISomeService myCglibCreator(){//创建增强器对象Enhancer enhancer=new Enhancer();//指定目标类,即父类 (因为cglib是通过创建子类来增强父类的)enhancer.setSuperclass(ISomeService.class);//设置回掉接口对象enhancer.setCallback(this);return (ISomeService) enhancer.create();}//回调方法@Overridepublic Object intercept(Object obj, Method method, Object[] args,MethodProxy proxy) throws Throwable {//调用目标方法Object result = method.invoke(target, args);if (result!=null) {result = ((String) result).toUpperCase();}return result;}}


package com.gqc.service;//主业务接口public interface ISomeService {//目标方法String dofirst();void  doSecond();}


package com.gqc.service;//目标类public class SomeServiceImpl implements ISomeService {public String dofirst() {System.out.println("执行dofirst");return "abcde";}public void doSecond() {System.out.println("执行doSecond");}}


package com.gqc.test;import com.gqc.factory.MyCglibFactory;import com.gqc.service.ISomeService;public class MyTest {public static void main(String[] args) {ISomeService service=new MyCglibFactory().myCglibCreator();String result = service.dofirst();System.out.println("result="+result);service.doSecond();}}