Spring中使用程序设定Bean以及关联bean

除了xml文件和属性文件以外,我们还可以在程序中直接来配置bean以及bean之间的联系,通过org.springframework.beans.MutablePropertyValues设置属性,然后将属性与Bean的类设置给org.springframework.beans.beans.factory.support.RootBeanDefinition,最后通过org.springframework.beans.factory.support.BeanDefinitionRegistry来注册Bean,下面我们还是以人物Role为实例:
[code]
public class TestBeanByProgrammer {
public static void main(String[] args) {
//通过MutablePropertyValues来设置属性
MutablePropertyValues properties=new MutablePropertyValues();
//设置name属性值为Mary
properties.addPropertyValue("name","Mary");
//设置health属性值为100
properties.addPropertyValue("health", 100);
//将properties赋予给Role类
RootBeanDefinition definition=new RootBeanDefinition(Role.class,properties);
BeanDefinitionRegistry reg=new DefaultListableBeanFactory();
//注册bean,设置bean的别名为role,相当与xml配置文件的id
reg.registerBeanDefinition("role", definition);
BeanFactory factory=(BeanFactory)reg;
Role role=(Role)factory.getBean("role");
System.out.println("人物名称是:" + role.getName() + ",人物的生命值是:"
+ role.getHealth());
if (role.getGoods() != null) {
System.out.println(role.getName() + "现有物品" + role.getGoods().size()
+ "件" + ",分别为:");
for (Goods obj : role.getGoods()) {
System.out.println(obj.getName());
}
} else
System.out.println("暂时没有任何物品!");
}
}
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值