spring笔记:第二章(通过xml装配bean)

通过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方法注入。
  1. 构造方法
    构造方法注入又包含普通配置和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方法注入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值