cglib javaSE 动态代理


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.junit.Test;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;

/**
 * desc:
 *
 * @author SHIPENGJUN
 * @date 2023/7/6
 */
public class AopTestCase {

    @Test
    public void t() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass.class);
        enhancer.setCallback(new DbsResponseProcess());
        targetClass t =  (targetClass) enhancer.create();
        System.out.println(t.t("oops"));
        System.out.println(t.tt("oops"));
    }

}

class DbsResponseProcess implements MethodInterceptor {
    
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        Object result = methodProxy.invokeSuper(o, args);
        if (method.isAnnotationPresent(DBSMethod.class)) {
            result = String.valueOf(result).toUpperCase();
        }
        return result;
    }

}

class targetClass {

    @DBSMethod
    public String t(String v) {
        return v;
    }

    public String tt(String v) {
        return v;
    }

}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface DBSMethod {

}

输出:

OOPS
oops

AspectJ 有注解更方便,为啥不用?因为纯JAVASE需要安装依赖包,烦。。

你可能感兴趣的:(java,web,java,开发语言)