Spring学习之装配bean

简单bean配置:
配置bean的简单属性,基本数据类型和string。
  <bean id="foo" class="...Foo">
        <property name="name">
              <value>tom</value>
        </property> 
  </bean>

引用其它bean
 <bean id="foo" class="...Foo">
        <property name="name">
              <ref bean="bar">
        </property> 
  </bean>
 <bean id="bar" class="...Bar">
  </bean>

内部bean
  <bean id="foo" class="...Foo">
        <property name="bar">
              <bean class="...Bar">
        </property> 
  </bean>
这种方式的缺点是你无法在其它地方重用这个bar实例,原因是它是专门为foo而用。

继承配置:
public class Student
public class Gradate extends Student
在beans.xml文件中体现配置
<!-- 配置一个学生对象 -->
<bean id="student" class="com.cz.inherit.Student">
    <property name="name" value="张三" />
    <property name="age" value="30"/>
</bean>
<!-- 配置Grdate对象 -->
<bean id="grdate" parent="student" class="com.cz.inherit.Gradate">
    <!-- 如果自己配置属性name,age,则会替换从父对象继承的数据  -->
    <property name="name" value="小明"/>
    <property name="degree" value="学士"/>
</bean>

通过构造函数注入值:
beans.xml 关键代码:
<!-- 配置一个雇员对象 -->
<bean id="employee" class="com.cz.constructor.Employee">
<!-- 通过构造函数来注入属性值 -->   
<constructor-arg index="0" type="java.lang.String" value="大明" />
</bean>

自动装配:

    1.byName寻找和属性名相同的bean,若找不到,则装不上。
<!-- 配置一个master对象 -->
<bean id="master" class="com.cz.autowire.Master" autowire="byName" >
<property name="name">
<value>张三</value>
</property>
</bean>
<!-- 配置dog对象 -->
<bean id="dog" class="com.cz.autowire.Dog">
<property name="name" value="小黄"/>
<property name="age" value="3"/>
</bean>
    2.byType:寻找和属性类型相同的bean,找不到,装不上,找到多个抛异常。
    3.constructor:查找和bean的构造参数一致的一个或多个bean,若找不到或找到多个,抛异常。按照参数的类型装配
    4.autodetect: 在constructor和byType之间选一个方式。
    5.defualt : 这个需要在<beans defualt-autorwire="指定" />
当你在<beans >指定了 default-atuowrite后, 所有的bean的 默认的autowire就是指定的装配方法;
如果没有在<beans defualt-autorwire="指定"/> 没有  defualt-autorwire=“指定” ,则默认是defualt-autorwire=”no”
    6.no : 不自动装配.   

分散配置:
beans.xml
说明: 当通过 context:property-placeholder 引入 属性文件的时候,有多个属性文件需要使用 , 号间隔.
<!-- 引入我们的db.properties文件 -->
<context:property-placeholder location="classpath:com/cz/dispatch/db.properties,classpath:com/cz/dispatch/db2.properties"/>
<!-- 配置一DBUtil对象 $占位符号 -->
<bean id="dbutil" class="com.cz.dispatch.DBUtil">
<property name="name" value="${name}" />
<property name="drivername" value="${drivername}" />
<property name="url" value="${url}" />
<property name="pwd" value="${pwd}" />
</bean>

db.properties:
name=scott
drivername=oracle:jdbc:driver:OracleDirver
url=jdbc:oracle:thin:@127.0.0.1:1521:oracle
pwd=tiger

猜你喜欢

转载自chenzheng8975.iteye.com/blog/1693854