ApplicationContext里面可以装载若干个Java对象。这些对象之间可以存在若干依赖关系。IoC会计算对象之间依赖关系,管理对象的初始化顺序,并根据这些依赖将被依赖对象注入到依赖对象中去。
XML的beans下面可以有若干上bean结点。
每个bean结点就声明容器中的一个Java对象。
bean结点的属性有:
id 在容器中,为对象命名唯一的名字
class 指定对象的类型
XML的形式,把Bean加载到IOC容器步骤
首先确保工程依赖中有spring-context-support
org.springframework
spring-context-support
4.0.9.RELEASE
创建Bean对象
IoC容器中的Bean对象需要遵守POJO标准。
代码如下:
package com.exodus.demo.ioc;
import java.util.List;
import java.util.Map;
public class TestData
{
private String name;
private Integer number;
private Map map;
private List list;
private String value;
public TestData()
{ }
public TestData(String name)
{
this.name = name;
}
//Getter And Setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Map getMap() {
return map;
}
public void setMap(Map map) {
this.map = map;
}
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
在IoC声明对象
<bean id="data" class="com.exodus.demo.ioc.TestData">
</bean>
上述bean没有指定构造参数,则会调用默认构造方法。
下面将会在初始化时,对bean进行new对象,并赋值
完整的XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="test" class="java.lang.String"/>
<!--调用TestData(String para1, String para2)的方法-->
<bean id="data" class="com.exodus.demo.ioc.TestData">
<constructor-arg value="test"/>
<constructor-arg value="19"/>
<!-- 会调用setName -->
<property name="name" value="test"/>
<!-- 会调用setValue -->
<property name="value" value="test"/>
<!-- 调用setList -->
<property name="list">
<list>
<value>a</value>
<value>b</value>
<value>c</value>
<ref bean="test"/> <!-- 将id为test,引用到这里 -->
</list>
</property>
<!-- 调用setMap -->
<property name="map">
<map>
<entry key="one" value="9.99"/>
<entry key="two" value="2.75"/>
<entry key="six" value="3.99"/>
</map>
</property>
</bean>
</beans>
获取bean
public class Main
{
public static void main(String[] args)
throws Exception
{
ApplicationContext context =
new ClassPathXmlApplicationContext("/ioc.xml");
String test = context.getBean("test", String.class);
}
}
本文深入探讨了Spring IoC容器如何管理对象之间的依赖关系,详细介绍了如何使用XML配置文件将Java对象加载到容器中,包括对象的创建、属性赋值以及依赖注入的过程。通过实例展示了如何在XML中定义Bean,以及如何通过容器获取并使用这些Bean。
895

被折叠的 条评论
为什么被折叠?



