Spring-创建bean

来源:互联网 发布:linux管道 文件 编辑:程序博客网 时间:2024/05/27 10:44
1.引入Jar包
2.创建applicatoncontext.xml文件
3.配置bean:
创建类
class user
{
string name;
//get,set必须要有
public void setName(string name)
{
this.name=name;
}

//set
}
spring框架启动的时候会检查配置文件中的bean,自动实例化bean对象并加载到内存中,id作为对象的名字
<bean id="userservice" class="xxx.xxx.user">
//个对象的属性赋值,相当于userservice.name="xie"
<property name="username">
<value>xie</value>
</property>
</bean>

<bean id="userservice1" class="xxx.xxx.user1">
//个对象的属性赋值,相当于userservice.name="xie"
<property name="username">
<value>xie</value>
//可以使用其他的bean作为参数
<property name="refedbean" ref="userservice"/>
</property>
</bean>

4.调用
1)得到spring application context
ApplicationContext ac=new classPathxmlapplicationcontext("applicationcontext.xml");
user us=(user)ac.getBean("userservice");

2)也可以通过Bean工厂获取 bean
BeanFactory bf=new XmlBeanFactory(new ClassPathResource("\"ioc\\\\beans.xml\""));
bf.getBean("student");
区别:
用factory的时候,在取bean的时候才会实例化。前者则是在实例化context的时候bean就会被实例化(仅在singleton模式下)。
factory延迟加载,省内存。

0 0
原创粉丝点击