Spring中Bean的配置

以下面的xml文件举例
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id = "role" class="spring.chapter.Role">
         </bean>
        <bean name="medicine" class="spring.chapter.Medicine"/>
        <bean class="spring.chapter.mary.Poison">
        <bean class="spring.chapter.mary.Poison">        
</beans>
第一个Bean的名称为role,第二个bean的名称为medicine,第三个bean的名称为spring.chapter.mary.Poison,第四个bean的名称为spring.chapter.mary.Poison#1
id和name的区别如下
id属性具有唯一性,每一个Bean只能对应一个id
name属性可以指定一个或多个名称,各个名称用逗号分开,第一个是默认为标示名称,后面的为这个Bean的别名。
例如
<bean name="medicine,001" class="spring.chapter2.Medicine">,这里只创建出来 一个Bean,注意只有一个。
每一个Bean中都有一个class属性。
Bean作用域
1singleton作用
<bean id="role" class="spring.chapter2.Role" scope="singleton">
该Bean的作用域设置为singleton,那么springIOC冗长中只会存在一个共享的bean实例。
即两次调用后,Role role = (Role)factory.getBean("role");Role role1 = (Role)factory.getBean("role");
role == role1 的值为 true
2prototype作用
prototype作用与部署的bean,每一次请求都会产生一个新的bean实例,
<bean id="role" class="spring.chapter.maryGame.Role" scope="prototype">或者,<singleton="false">
role == role1 的值为 false
还有其他作用域,这里不再介绍

Bean的属性,spring有两种注入方式,一种set注入,一种构造子注入。在配置文件总选择那种方式取决于实体类。
(1)实体类的每个变量都有set方法,此时使用property属性来配置
(2)史泰龙使用构造函数来配置,此时使用<constructor-arg>属性来配置
若一个类中既有构造方法,又有set方法
如下:package chapter1;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
public class Hello {

private String msg;
private int example;
public Hello(String msg,int example)
{
this.msg = msg;
this.example = example;
}
public void setExample(int example) {
this.example = example;
}
public void setMsg(String msg)
{
this.msg = msg;
}
public void sayHello()
{
System.out.println(msg);
System.out.println(example);
}
public static void main(String[] args)
{
Resource res = new ClassPathResource("chapter1/bean.xml");
BeanFactory factory = new XmlBeanFactory(res);
Hello hello = (Hello)factory.getBean("helloBean");
hello.sayHello();

}
}

配置文件为:<bean id="helloBean" class="chapter1.Hello">
<property name="example" value="20"></property>
<property name="msg" value="abc"></property>
<constructor-arg index="0" value="示例"></constructor-arg>
<constructor-arg index="1" value="10">
</constructor-arg>
</bean>或者
<bean id="helloBean" class="chapter1.Hello">
<constructor-arg index="0" value="示例"></constructor-arg>
<constructor-arg index="1" value="10">
</constructor-arg>
<property name="example" value="20"></property>
<property name="msg" value="abc"></property>
</bean>
则最后输出结果为:abc 20
可见是set方法起作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值