spring18-1:采用jdk的动态代理 proxy。
生活随笔
收集整理的這篇文章主要介紹了
spring18-1:采用jdk的动态代理 proxy。
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
?
接口
public interface UserService {void addUser();void updateUser(); }接口的實現(xiàn)類?
public class UserServiceImpl implements UserService {@Overridepublic void addUser() {System.out.println("adduser...");}@Overridepublic void updateUser() {System.out.println("updateUser...");}}?切面
public class MyAspect {public void before(){System.out.println("事務開啟");}public void after(){System.out.println("事務開啟");} }工廠類,創(chuàng)建代理類?
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy;public class BeanFactory {public static UserService createProxyService(){final UserService userService = new UserServiceImpl();final MyAspect myAspect = new MyAspect();UserService userServiceProxy = (UserService)Proxy.newProxyInstance(BeanFactory.class.getClassLoader(),userService.getClass().getInterfaces(), new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {myAspect.before();Object res = method.invoke(userService, args);myAspect.after();return res;}});return userServiceProxy;}}測試類?
import org.junit.Test;public class TestProxy {@Testpublic void test(){UserService us = BeanFactory.createProxyService();us.addUser();us.updateUser();} }?
總結
以上是生活随笔為你收集整理的spring18-1:采用jdk的动态代理 proxy。的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《编码:隐匿在计算机软硬件背后的语言(美
- 下一篇: spring18-2:采用cglib字节