2017-06-16 276 views
0

我是Spring的新手。我有下面的Person bean,名稱,地址和年齡作爲屬性。現在我想在我的自定義BeanFactoryPostProcessor的Person bean中添加一個名爲gender的新屬性。我的人員bean實現了AttributeAccessor。如何在運行時在spring中爲bean添加屬性

XML配置文件

<bean id="PersonBean" class="com.mkyong.common.Person">    
    <property name="name" value="mkyong"></property> 
    <property name="address" value="address ABC"></property> 
    <property name="age" value="29"></property>       
</bean>                 
<bean class="com.mkyong.common.CustomBeanFactory"></bean> 

定製的BeanFactoryPostProcessor

public class CustomBeanFactory implements BeanFactoryPostProcessor { 
@Override 
public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0) throws BeansException { 
    BeanDefinition beanDefinition = arg0.getBeanDefinition("PersonBean"); 
    beanDefinition.setAttribute("gender", "Male"); 
    }                  
} 

Person類
enter code here

public class Person implements AttributeAccessor{ 

private String name; 
private String address; 
private int age; 

public Person(){ 
    System.out.println("Creating bean Person "+this); 
} 

public String getName() { 
    return name; 
} 

public void setName(String name) { 
    this.name = name; 
} 

public String getAddress() { 
    return address; 
} 

public void setAddress(String address) { 
    this.address = address; 
} 

public int getAge() { 
    return age; 
} 

public void setAge(int age) { 
    this.age = age; 
} 

@Override 
public String[] attributeNames() { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public Object getAttribute(String arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public boolean hasAttribute(String arg0) { 
    // TODO Auto-generated method stub 
    return false; 
} 

@Override 
public Object removeAttribute(String arg0) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public void setAttribute(String arg0, Object arg1) { 
    // TODO Auto-generated method stub 
} 
} 

客戶端程序

public static void main(String [] arg){ 
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"Spring-Autoscan.xml"}); 

    Person personObj = (Person)context.getBean("PersonBean"); 
    System.out.println("Value of gender attribute "+personObj.getAttribute("gender")); 
} 

如果我訪問的性別我得到空

請讓我知道如何配置和動態獲取屬性。

回答

0

您的setAttribute()方法爲空。它不存儲該值。

public void setAttribute(String arg0, Object arg1) { 
    // TODO Auto-generated method stub 
} 

在裏面創建一個Map您可以在其中存儲值並將其取回。像這樣

private Map<String, Object> map = new HashMap<>(); 

public void setAttribute(String arg0, Object arg1) { 
    map.put(arg0, arg1); 
} 

public Object getAttribute(String arg0) { 
    return map.get(arg0); 
} 
+0

是的,我同意。但是在Custom BeanFactoryPostProcessor類中使用beanDefinition.setAttribute方法有什麼用處 –

相關問題