springbean配置:Bean的配置来源: 发布时间:星期四, 2009年2月12日 浏览:28次 评论:0
以下面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" ="spring.chapter.Role"> </bean> <bean name="medicine" ="spring.chapter.Medicine"/> <bean ="spring.chapter.mary.Poison"> <bean ="spring.chapter.mary.Poison"> </beans> 第个Bean名称为role,第 2个bean名称为medicine第 3个bean名称为spring.chapter.mary.Poison,第 4个bean名称为spring.chapter.mary.Poison#1 id和name区别如下 id属性具有唯性每个Bean只能对应个id name属性可以指定个或多个名称各个名称用逗号分开第个是默认为标示名称后面为这个Bean别名 例如 <bean name="medicine,001" ="spring.chapter2.Medicine">,这里只创建出来个Bean,注意只有个 每个Bean中都有个属性 Bean作用域 1singleton作用 <bean id="role" ="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" ="spring.chapter.maryGame.Role" scope="prototype">或者<singleton="false"> role role1 值为 false 还有其他作用域这里不再介绍 Bean属性spring有两种注入方式种注入种构造子注入在配置文件总选择那种方式取决于实体类 (1)实体类每个变量都有思路方法此时使用property属性来配置 (2)史泰龙使用构造来配置此时使用<constructor-arg>属性来配置 若个类中既有构造思路方法又有思路方法 如下: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 Hello { private String msg; private example; public Hello(String msg, example) { this.msg = msg; this.example = example; } public void Example( example) { this.example = example; } public void Msg(String msg) { this.msg = msg; } public void sayHello { .out.prln(msg); .out.prln(example); } public void (String args) { Resource res = ClassPathResource("chapter1/bean.xml"); BeanFactory factory = XmlBeanFactory(res); Hello hello = (Hello)factory.getBean("helloBean"); hello.sayHello; } } 配置文件为:<bean id="helloBean" ="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" ="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 可见是思路方法起作用 0
相关文章
读者评论发表评论 |