通过xml装配bean
工具
借助Spring Tool Suite创建xml文件。可以自动引入xds规范,可以校验xml完整性。
xml结构
xml包含两部分:第一部分是文档头(xds规范引用区域),一部分是文档体(配置编写区域)。
装配一个简单bean
实例
<bean class="类名称"></bean>
<bean id-"beanName" class="类名称"></bean>
当配置中未指定id时,自动创建id。命名规范:类名称首字母小写+#+序号(0开始)
当配置中指定id时,采用配置内容作为bean的唯一标识。
注入bean属性
注入方式有两种:1.构造方法注入。2。set方法注入。
- 构造方法
构造方法注入又包含普通配置和c命令配置。
1.1. 普通配置
xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:c="http://www.springframework.org/schema/c"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<bean id="sgtPeppers" class="chujie.demo.spring.ioc.soundsystem.SgtPeppers" />
<bean id="simPeppers" class="chujie.demo.spring.ioc.soundsystem.SgtPeppers" />
<bean id="txtPeppers" class="chujie.demo.spring.ioc.soundsystem.SgtPeppers" />
</beans>
测试类
package chujie.demo.spring.ioc.soundsystem;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-beans.xml"})
public class CDPlayTest {
@Autowired
private CompactDisc sgtPeppers;
@Autowired
private CompactDisc simPeppers;
@Autowired
private CompactDisc txtPeppers;
@Test
public void test() {
System.out.println("sgt="+sgtPeppers.hashCode());
System.out.println("sim="+simPeppers.hashCode());
System.out.println("txt="+txtPeppers.hashCode());
}
}
执行结果
sgt=425194741
sim=1569918418
txt=1634764284
实例重点在于测试类的@ContextConfiguration(locations={"classpath:spring-beans.xml"}) 配置,用于加载配置文件使用。
1.2. c命令配置
3. set方法注入