Spring 入门之属性配置

来源:互联网 发布:什么叫对冲基金 知乎 编辑:程序博客网 时间:2024/05/18 11:45
一.创建Spring的IOC容器
applicationContext代表IOC容器
IOC容器分为两种:
a.BeanFactory:IOC容器的基本实现
b.applicationContext:提供更多高级特性,几乎所有场合都会直接用applicationContext
applicationContext主要有两个实现类:
1).ClassPathXmlApplicationContext:从类路径下加载配置文件
2).FileSystemXmlApplicationContext:从文件系统中加载配置文件
ClassPathXmlApplicationContext是applicationContext借口的实现类,从类路径下加载配置文件


2.从IOC容器中获取Bean实例
context.getBean(a)
a:可以用id,也可以用类型(XXX.class)


利用id定位到IOC容器中的bean
利用类型返回IOC容器中的Bean,但要求IOC容器中必须只能有一个该类型的Bean


二:bean的属性注入方式


1.setter方法注入(最常用的方式)
2.构造方法注入
<!-- 使用构造器植入属性值可以指定参数的位置和参数的类型以区分重载的构造器 -->
<bean id="car" class="com.nsu.spring.beans.Car">
<constructor-arg value="audi" index="0"></constructor-arg>
<constructor-arg value="gansu" index="1"></constructor-arg>
<constructor-arg value="30000" index="2"></constructor-arg>
</bean>
<bean id="car2" class="com.nsu.spring.beans.Car">
<constructor-arg value="baoma" type="java.lang.String"></constructor-arg>
<constructor-arg value="gansu" type="java.lang.String"></constructor-arg>
<constructor-arg value="240" type="int"></constructor-arg>


1).如果字面值包含特殊字符,可以使用<![CDATA[]]>包裹起来
for:
<value><![CDATA[<gansu>]]></value>
2).属性值可以通过value子节点进行配置
for:
or
<constructor-arg type="int">
<value>245</value>
</constructor-arg>
3).可以使用property的ref属性建立bean之间的引用关系
4).为级联属性赋值(注意:属性需要先初始化后才能为级联属性赋值,否则会出现异常,和struts2不同)
<property name="car" ref="car"></property>
<property name="car.maxSpeed" value="240"></property>


3.使用list节点来对内置属性赋值


<property name="cars">
<list>
<ref bean="car"></ref>
<ref bean="car2"></ref>
</list>
</property>


4.使用map节点及map的entry子节点配置map类型的成员变量


<property name="cars" >
<map>
<entry key="AA" value-ref="car"></entry>
<entry key="BB" value-ref="car2"></entry>
</map>
</property>


5.使用props和prop子节点来为Properties属性赋值


<property name="properties">
<props>
<prop key="user">root</prop>
<prop key="passowrd">1234</prop>
<prop key="jdbcUrl">jdbc:mysql:///test</prop>
<prop key="driverClass">com.mysql.jdbc.Driver</prop>
</props>
</property>


6.配置单例的集合bean,以供多个bean进行引用,需要导入util命名空间


<util:list id="cars">
<ref bean="car"></ref>
<ref bean="car2"></ref>
</util:list>


        <bean id="person2" class="com.nsu.spring.beans.collection.Person">
<property name="name" value="jack"></property>
<property name="age" value="28"></property>
<property name="cars" ref="cars"></property>
</bean>


7.通过p命名空间为bean的属性赋值,需要先导入P命名空间,相对于传统的配置方式更加的简洁


<bean id="person3" class="com.nsu.spring.beans.collection.Person" p:age="25" p:cars-ref="car" p:name="ok">
</bean>



0 0
原创粉丝点击