您好,登錄后才能下訂單哦!
怎么在Spring AOP中手動實現(xiàn)動態(tài)代理?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
目標(biāo)類的接口
public interface UserService { public void addUser() ; public void updateUser(); public void deleteUser(); }
目標(biāo)類接口的實現(xiàn)
public class UserServiceImpl implements UserService { @Override public void addUser() { System.out.println("addUser"); } @Override public void updateUser() { System.out.println("updateUser"); } @Override public void deleteUser() { System.out.println("deleteUser"); } }
通知類
public class MyAspect { public void before(){ System.out.println("before"); } public void after(){ System.out.println("after"); } }
代理類
public class MyBeanFactory { public static UserService createService(){ //1.目標(biāo)類 final UserService userService = new UserServiceImpl() ; //2.切面類 final MyAspect myAspect = new MyAspect(); // 切入點和切面類結(jié)合 // 三個參數(shù) // 1. loader ,類加載器 運行是加載,用類加載器將其加載到內(nèi)存 // 2. interfaces 代理類需要實現(xiàn)的所有接口 // 3. invocationHandler 處理類,一般采用匿名內(nèi)部類 // 提供了invoke方法 代理類每個方法執(zhí)行時都將調(diào)用一次invoke ,又有三個參數(shù) // 1. Object proxy 代理對象 // 2. Method method 代理對象方法的反射 // 3. Object[] args 方法的實際參數(shù) UserService proxyService = (UserService) Proxy.newProxyInstance(MyBeanFactory.class.getClassLoader(), userService.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(method.getName()); myAspect.before(); Object obj = method.invoke(userService, args); myAspect.after(); return obj ; } }); return proxyService ; } }
測試類
public class UserServiceImplTest { @org.junit.jupiter.api.Test public void demo() throws Exception { UserService userService = MyBeanFactory.createService(); userService.addUser(); userService.deleteUser(); userService.updateUser(); } }
結(jié)果
addUser
before
addUser
after
deleteUser
before
deleteUser
after
updateUser
before
updateUser
after
Process finished with exit code 0
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。