如何在Spring中运行时向bean添加属性

时间:2017-06-16 11:35:46

标签: java spring

我是Spring的新手。我有下面的Person bean,名称,地址和年龄作为属性。现在我想在我的自定义BeanFactoryPostProcessor中向Person bean添加一个名为gender的新属性。我的人bean实现了AttributeAccessor。

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");
    }                                                                       
}

人员班           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"));
}

如果我访问性别,我将无效

请让我知道如何动态设置和获取属性。

1 个答案:

答案 0 :(得分: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);
}