?
在問答頻道 有朋友問 《如何為spring代理類設置屬性值》 ?就寫了個小工具 供使用。思想就不講了。
現在有一個bean包含了私有屬性,如下:
- @Component ??
- public ? class ?Bean?{??
- ????String?name;??
- ??
- ???? public ?String?getName()?{??
- ???????? return ?name;??
- ????}??
- ??
- ???? public ? void ?setName(String?name)?{??
- ???????? this .name?=?name;??
- ????}??
- ??????
- }??
它被AOP配置過代理,代理配置為:
?
- <aop:pointcut?expression= "execution(*?com..*Bean.*(..))" ??
- ????????????id= "txBean" ?/>??
?現在對它進行測試:
- public ? class ?BeanTest? extends ?SpringContextTestCase{??
- ???? @Autowired ??
- ???? private ?Bean?bean;??
- ???? @Test ??
- ???? public ? void ?testBean(){??
- ????????bean.setName( "dylan" );??
- ????????System.out.println(bean.name);??
- ????????System.out.println(bean.getName());??
- ????}??
- }??
?這里的測試結果中,第一個輸出為null,第二個輸出為dylan,
由于項目中需要直接通過bean.name的方式來獲取屬性值,卻一直都只能得到null,請問如何才能獲取到我所期望的值"dylan"呢
?
?
默認是沒有辦法的。我幫你寫了個AOP切面 幫你完成設置屬性。?
- import ?java.beans.PropertyDescriptor;??
- import ?java.lang.reflect.Field;??
- import ?java.lang.reflect.Method;??
- ??
- import ?org.aspectj.lang.JoinPoint;??
- import ?org.aspectj.lang.annotation.After;??
- import ?org.aspectj.lang.annotation.Aspect;??
- import ?org.springframework.aop.support.AopUtils;??
- import ?org.springframework.beans.BeanUtils;??
- import ?org.springframework.core.annotation.Order;??
- ??
- @Aspect ??
- @Order (Integer.MIN_VALUE)??
- public ? class ?SetterAspect?{??
- ??????
- ???? @After (value= "execution(*?*.set*(*))?&&?args(value)" ,?argNames= "value" )??
- ???? public ? void ?after(JoinPoint?jp,?Object?value)?{??
- ????????Object?proxy?=?jp.getThis();??
- ????????Object?target?=?jp.getTarget();??
- ??????????
- ???????? if (AopUtils.isAopProxy(proxy))?{ //只有代理對象才需要處理 ??
- ??????????????
- ???????????? try ?{??
- ????????????????Class<?>?proxyClass?=?proxy.getClass();??
- ????????????????Class<?>?targetClass?=?target.getClass();??
- ????????????????String?methodName?=?jp.getSignature().getName();??
- ??????????????????
- ????????????????Method?m?=?BeanUtils.findDeclaredMethod(proxyClass,?methodName,? new ?Class[]{value.getClass()});??
- ????????????????PropertyDescriptor?descriptor?=?BeanUtils.findPropertyForMethod(m);??
- ????????????????String?propName?=?descriptor.getName();??
- ??????????????????
- ????????????????Field?f?=?targetClass.getClass().getDeclaredField(propName);??
- ???????????????? if (f?!=? null )?{??
- ????????????????????f.setAccessible( true );??
- ????????????????????f.set(proxy,?value);??
- ????????????????}??
- ????????????}? catch ?(Exception?e)?{??
- ????????????????e.printStackTrace(); //記錄好異常進行處理 ??
- ????????????}??
- ????????}??
- ????}??
- ??
- } ?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
