在問答頻道 有朋友問《如何爲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();//記錄好異常進行處理
- }
- }
- }
- }