对目标方法实现前置或者后置增强,
是在程序动态运行时加入增强方法的。
1. 目标类
package com.lovely.proxy.cglib;/*** 目标类* @author echo lovely* @date 2020/7/26 15:20*/
public class Target {public void save() {System.out.println("sve running...");}
}
2. 增强类
package com.lovely.proxy.cglib;/*** 增强类 拿before和afterReturning对Target中save方法增强* @author echo lovely* @date 2020/7/26 15:20*/
public class Advice {public void before() {System.out.println("前置增强...");}public void afterReturning() {System.out.println("后置增强...");}}
3. 测试demo
package com.lovely.proxy.cglib;import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;import java.lang.reflect.Method;/*** cglib test* @author echo lovely* @date 2020/7/26 15:18*/
public class ProxyText {public static void main(String[] args) {// 创建目标类final Target target = new Target();// 增强类final Advice advice = new Advice();// 1 创建增强器Enhancer enhancer = new Enhancer();// 2 设置父类(目标类)enhancer.setSuperclass(target.getClass());// 3 设置回调enhancer.setCallback(new MethodInterceptor() { // 方法拦截器public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {advice.before(); // 方法增强Object returnValue = method.invoke(target, objects); // 调用目标方法advice.afterReturning(); // 后置方法return returnValue;}});// 4 创建代理对象Target proxy = (Target) enhancer.create();proxy.save();}}