spring18-2:采用cglib字节码实现代理
生活随笔
收集整理的這篇文章主要介紹了
spring18-2:采用cglib字节码实现代理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
沒有接口,只有實現類。
采用字節碼增強框架cglib, 在運行時,創建目標類的子類,從而對目標類進行增強。
實現類,沒有實現任何接口
public class UserServiceImpl {public void addUser() {System.out.println("cglib adduser...");}public void updateUser() {System.out.println("cglib updateUser...");} }切面?
public class MyAspect {public void before(){System.out.println("cglib 事務開啟");}public void after(){System.out.println("cglib 事務結束");} }?工廠,產生代理類
import java.lang.reflect.Method;import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy;public class BeanFactory {public static UserServiceImpl createProxyService(){final UserServiceImpl userService = new UserServiceImpl();final MyAspect myAspect = new MyAspect();// 核心類 Enhancer enhancer = new Enhancer();// 確定父類enhancer.setSuperclass(UserServiceImpl.class);// 設置回調函數enhancer.setCallback(new MethodInterceptor() {// 等效于jdk中的invoke方法@Overridepublic Object intercept(Object proxy, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {myAspect.before();// 執行目標類的方法Object obj = method.invoke(userService, args);myAspect.after();return obj;}});// 創建代理UserServiceImpl proxyService = (UserServiceImpl)enhancer.create();return proxyService;} }測試類:?
import org.junit.Test;public class TestProxy {@Testpublic void test(){UserServiceImpl us = BeanFactory.createProxyService();us.addUser();us.updateUser();} }?
總結
以上是生活随笔為你收集整理的spring18-2:采用cglib字节码实现代理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spring18-1:采用jdk的动态代
- 下一篇: spring18-3: 工厂bean代理