Spring独自のcglibを使用してプロキシクラスを作成するインスタンスについて

1275 ワード

プロキシクラスを作成する方法:
    //import org.springframework.cglib.proxy.Enhancer;
    //import org.springframework.cglib.proxy.MethodInterceptor;
    //import org.springframework.cglib.proxy.MethodProxy;


    /**
     *      
     *
     * @param targetBean  Bean
     * @return   Bean
     */
    private Object createProxyBean(final Object targetBean) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetBean.getClass());
        enhancer.setUseCache(true);
        enhancer.setInterceptDuringConstruction(false);
        enhancer.setCallback((MethodInterceptor) (bean, method, args, methodProxy) -> {
            System.err.println("   ");
            Object result = methodProxy.invokeSuper(bean, args);
            System.err.println("   ");
            return result;
        });
        Object targetProxyBean = enhancer.create();
        return targetProxyBean;
    }

テストの実践:
  • テストクラスの作成:
  •     public class Test{
            public void say() {
                System.err.println("Hello");
            }
        }
  • テスト:
  •     Test test = (Test) createProxyBean(new Test());
        test.say();
  • 出力結果
  •    
    Hello