Spring:IoC 用法(八、<bean>用法)

本文详细介绍了Spring框架中XML配置的各项特性,包括&lt;bean&gt;元素的属性与子元素、&lt;property&gt;元素的使用及不同类型的注入方式等,并通过丰富的示例代码展示了这些配置的实际应用。

XML 配置详解

1、<bean> 属性

作用:一个 <bean>元素对应一个 class 类

1)、id

作用:<bean>的全局唯一标识,也是 <bean>的别名,没有 id 时自动使用类名首字母小写(注入时使用)

测试:

测试 Controller

public class TestController {

    public String testController() {
        return "成功注入!!!";
    }
}

配置类

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean id="testController" class="test.define.controller.TestController"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
@ActiveProfiles("pro")
public class Test {

    @Autowired
    private TestController controller;

    @org.junit.Test
    public void testXMLConfig() {
        String data = controller.testController();
        System.out.println(data);
    }
}

结果

成功注入!!!

2)、name

作用:<bean>的别名,可以同时存在多个,多个时使用逗号分隔(注入时使用

测试:

测试Controller

public class TestController {

    public String testController() {
        return "成功注入!!!";
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean id="testController" name="c1,c2" class="test.define.controller.TestController"></bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
@ActiveProfiles("pro")
public class Test {

    @Autowired
    @Qualifier("c1")
    private TestController c1;

    @Autowired
    @Qualifier("c2")
    private TestController c2;

    @org.junit.Test
    public void testXMLConfig() {
        String data;
        data = c1.testController();
        System.out.println("c1: " + data);

        data = c2.testController();
        System.out.println("c2: " + data);
    }
}

3)、class

作用:<bean>和 class的连接(实例化时使用

测试:无

4)、parent

作用:将两个不相干的类,设置成父子关系

测试:

测试Controller基类

public class BaseController {

    public BaseController(){
        System.out.println("this is BaseController");
    }
}

测试Controller

public class TestController {

    public String testController() {
        return "成功注入!!!";
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- 注入Controller基类 -->
    <bean id="baseController" class="test.define.base.BaseController"/>
    <!-- 设置关联关系 -->
    <bean id="testController" name="c1,c2" class="test.define.controller.TestController" parent="baseController"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
@ActiveProfiles("pro")
public class Test {

    @Autowired
    private TestController controller;

    @org.junit.Test
    public void testXMLConfig() {
        String data = controller.testController();
        System.out.println("c1: " + data);
    }
}
结果

this is BaseController
c1: 成功注入!!!

5)、abstract

作用:模板的一种用法,有如下特点

abstract 修饰的类,不允许定义 <bean>,除非使用 abstract=true 修饰<bean>

abstract 修饰的<bean>不会被预加载,不允许注入,值允许引用

三种情况:

1、抽象类定义模板

2、普通类定义模板

3、没有匹配类的末班

测试:(抽象类模板)

定义抽象类(模板)

public abstract class AbstractTemplate {

    private String id;
    private String name;

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}

定义普通类(被初始化)

public class TestController {

    private String id;
    private String name;
    private int age;

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return id + "-----" + name + "-----" + age;
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- 抽象类的模板 -->
    <!-- 定义模板:初始化模板参数 -->
    <bean id="template" class="test.define.abstrac.AbstractTemplate" abstract="true">
        <property name="id" value="ID"/>
        <property name="name" value="名称"/>
    </bean>

    <!-- 使用模板初始化参数 -->
    <bean id="testController" class="test.define.controller.TestController" parent="template"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController controller;

    @org.junit.Test
    public void testXMLConfig() {
        System.out.println(controller);
    }
}

结果

ID-----名称-----0


测试:(测试普通类模板)

定义普通类(模板)

public class Template {

    private String id;
    private String name;

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
}

定义普通类(被初始化)

public class TestController {

    private String id;
    private String name;
    private int age;

    public void setId(String id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String toString() {
        return id + "-----" + name + "-----" + age;
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- 普通类的模板 -->
    <!-- 定义模板:初始化模板参数 -->
    <bean id="template" class="test.define.abstrac.Template" abstract="true">
        <property name="id" value="ID"/>
        <property name="name" value="名称"/>
    </bean>

    <!-- 使用模板初始化参数 -->
    <bean id="testController" class="test.define.controller.TestController" parent="template"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController controller;

    @org.junit.Test
    public void testXMLConfig() {
        System.out.println(controller);
    }
}

结果

ID-----名称-----0

测试:(测试单纯模板)

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- 纯模板 -->
    <!-- 定义模板:初始化模板参数 -->
    <bean id="template"  abstract="true">
        <property name="id" value="ID"/>
        <property name="name" value="名称"/>
    </bean>

    <!-- 使用模板初始化参数 -->
    <bean id="testController" class="test.define.controller.TestController" parent="template"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController controller;

    @org.junit.Test
    public void testXMLConfig() {
        System.out.println(controller);
    }
}

结果

ID-----名称-----0

6)、scope:(最早期版本的 singleton 属性已废除,现在替换为 scope="singleton")

作用:不同类型作用域实例化时有所区别,Ioc部分分为两种类型(其他类型此处不说明)

              singleton:单例(所有单例<bean>在服务启动时会进行预加载实例)

              prototype:原型(多例,使用时创建实例)

单例测试:

测试Controller

public class TestController {

    public String testController() {
        return "成功注入!!!";
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean class="test.define.controller.TestController" scope="singleton"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController c1;

    @Autowired
    private TestController c2;

    @org.junit.Test
    public void testXMLConfig() {
        String data;
        data = c1.testController();
        System.out.println("c1: " + data);
        data = c2.testController();
        System.out.println("c2: " + data);
        if(c1 == c2){
            System.out.println("单例模式实例相等。");
        }else {
            System.out.println("原型模式实例不相等。");
        }
    }
}
结果
c1: 成功注入!!!
c2: 成功注入!!!
单例模式实例相等。

原型测试:

配置文件:修改配置文件后,重新执行测试类,查看执行结果

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean class="test.define.controller.TestController" scope="prototype"/>
</beans>
结果
c1: 成功注入!!!
c2: 成功注入!!!
原型模式实例不相等。


7)、lazy-init

作用:延迟加载 <bean>,优先级高于<beans > 的 default-lazy-init 属性

          当<bean>与<beans>冲突时,优先考虑<bean>级别的 lazy-init

          有两个属性可以选择:true、false

测试:无(通过启动时间或日志的方式判断)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean class="test.define.controller.TestController" lazy-init="true"/>

</beans>

8)、autowire

作用:表示<bean>自动注入的方式,有五种选择:

              no:禁止自动注入(默认)

              defalut:继承容器级别<beans> 的 default-autowire 属性

              byName:根据别名注入(ID也属于别名的一种)(方法注入)

              byType:根据类型注入(方法注入)

              constructor:根据类型注入(构造方法注入)

测试:(autowire = no

定义Controller控制层

public class TestController {

    // 当 autowire="no" 时,注入肯定失败
    // 使用 @Autowired 确保注入成功
    @Autowired
    private TestService testService;

    public String testController() {
        return testService.testService();
    }
}

定义Service服务层接口

public interface TestService {

    String testService();
}

定义Service服务层接口实现

public class TestServiceImpl implements TestService {

    public String testService() {
        return "this is TestServiceImpl";
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- 当前类禁止自动注入,此自动注入非彼自动注入,此自动注入可以去掉注解方式注入(完全自动注入) -->
    <bean class="test.define.controller.TestController" autowire="no"/>

    <bean id="testServiceImpl" class="test.define.service.impl.TestServiceImpl"/>

</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController testController;

    @org.junit.Test
    public void testXMLConfig() {
        String data = testController.testController();
        System.out.println(data);
    }
}

结果:因为使用了@Autowired,确保了测试成功,否则注入失败

this is TestServiceImpl


测试:(autowire = default

<继承容器级别<beans> 的 default-autowire 属性>


测试:(autowire = byName

测试Controller控制层

public class TestController {

    private TestService service;

    public String testController() {
        return service.testService();
    }

    // byName 方法注入方式,参数的名称必须与被注入 <bean> 的别名相同
    public void setTestService(TestService testService) {
        this.service = testService;
    }
}

测试Service服务层接口

public interface TestService {

    String testService();
}

测试Service服务层接口实现

public class TestServiceImpl implements TestService {

    public String testService() {
        return "this is TestServiceImpl";
    }
}
配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- byName 方法注入方式,根据别名注入(完全自动注入),别名必须与参数的名相同 -->
    <bean class="test.define.controller.TestController" autowire="byName"/>

    <bean id="testService" class="test.define.service.impl.TestServiceImpl"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController testController;

    @org.junit.Test
    public void testXMLConfig() {
        String data = testController.testController();
        System.out.println(data);
    }
}

结果

this is TestServiceImpl


测试:(autowire = byType

测试Controller控制层

<同 autowire = byName>

测试Service服务层接口

<同 autowire = byName>

测试Service服务层接口实现

<同 autowire = byName>

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- byType 方法注入方式,根据类型注入,只要类型与参数的名相同,即注入 -->
    <bean class="test.define.controller.TestController" autowire="byType"/>

    <!-- 根据类型注入,不需要ID和别名 -->
    <bean class="test.define.service.impl.TestServiceImpl"/>
</beans>

测试类

<同 autowire = byName>

结果

<同 autowire = byName>


测试:(autowire = constructor

测试Controller控制层

public class TestController {

    private TestService service;

    public String testController() {
        return service.testService();
    }

    // 过渡
    public TestController() {

    }

    // autowire="constructor" 构造方法注入方式,只要有与参数类型相匹配的,即注入
    public TestController(TestService testService) {
        this.service = testService;
    }
}

测试Service服务层接口

public interface TestService {

    String testService();
}

测试Service服务层接口实现

public class TestServiceImpl implements TestService {

    public String testService() {
        return "this is TestServiceImpl";
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- byType 方法注入方式,根据类型注入,只要类型与参数的名相同,即注入 -->
    <bean class="test.define.controller.TestController" autowire="constructor"/>

    <!-- 根据类型注入,不需要ID和别名 -->
    <bean class="test.define.service.impl.TestServiceImpl"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController testController;

    @org.junit.Test
    public void testXMLConfig() {
        String data = testController.testController();
        System.out.println(data);
    }
}

结果

this is TestServiceImpl

9)、autowire-candidate

作用:是否参与注入,当一个接口有多个实现类时,可能会导致注入冲突,该属性有三个选择

              default:忽略错误(运行时可能报错)

              true:参与注入

              false:不参与注入

测试:(已类型注入为例)

测试Controller控制层

public class TestController {

    private TestService service;

    public String testController() {
        return service.testService();
    }

    public void setTestService(TestService testService) {
        this.service = testService;
    }
}

测试Service服务层接口

public interface TestService {

    String testService();
}

测试Service服务层接口实现类

public class TestServiceImpl implements TestService {

    public String testService() {
        return "this is TestServiceImpl";
    }
}
public class ProServiceImpl implements TestService {

    public String testService() {
        return "this is ProServiceImpl";
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- byType 方法注入方式,根据类型注入,只要类型与参数的名相同,即注入 -->
    <bean class="test.define.controller.TestController" autowire="byType"/>

    <!-- 实现了同一个接口的两个类 -->
    <!-- 第一个实现类 -->
    <bean class="test.define.service.impl.TestServiceImpl"/>

    <!-- 第二个实现类:autowire-candidate="false" 不参与注入 -->
    <bean class="test.define.service.impl.ProServiceImpl" autowire-candidate="false"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController testController;

    @org.junit.Test
    public void testXMLConfig() {
        String data = testController.testController();
        System.out.println(data);
    }
}

结果

this is TestServiceImpl

10)、primary

作用:首选注入,当一个接口有多个实现类时,可能会导致注入冲突,有三个选择

测试:(已注解注入为例)

测试Controller控制层

public class TestController {

    @Autowired
    private TestService service;

    public String testController() {
        return service.testService();
    }
}

测试Service服务层接口

public interface TestService {

    String testService();
}

测试Service服务层接口实现

public class TestServiceImpl implements TestService {

    public String testService() {
        return "this is TestServiceImpl";
    }
}
public class ProServiceImpl implements TestService {

    public String testService() {
        return "this is ProServiceImpl";
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- byType 方法注入方式,根据类型注入,只要类型与参数的名相同,即注入 -->
    <bean class="test.define.controller.TestController"/>

    <!-- 实现了同一个接口的两个类 -->
    <!-- 第一个实现类 -->
    <bean class="test.define.service.impl.TestServiceImpl"/>

    <!-- 第二个实现类:primary="true" 首选注入 -->
    <bean class="test.define.service.impl.ProServiceImpl" primary="true"/>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController testController;

    @org.junit.Test
    public void testXMLConfig() {
        String data = testController.testController();
        System.out.println(data);
    }
}

结果

this is ProServiceImpl

11)、depends-on

作用:实例当前<bean>之前,先实例另一个<bean>(在使用过程中很少出现类似情况)

测试:(使用三个普通类测试,不要管类的名字)

测试Controller控制层

public class TestController {

    public String testController() {
        return TestServiceImpl.getValue();
    }
}

测试初始化数据

public class TestServiceImpl {

    private static String value = "初始化数据!!!";

    public static void setValue(String value) {
        TestServiceImpl.value = value;
    }

    public static String getValue() {
        return value;
    }
}

测试覆盖数据

public class InitClass {

    public InitClass() {
        TestServiceImpl.setValue("覆盖初始化数据!!!");
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean id="init" class="test.define.init.InitClass"/>

    <!-- depends-on="init" 实例当前<bean>之前,先实例 别名 = init 的 <bean> -->
    <bean class="test.define.controller.TestController" depends-on="init"/>
</beans>

测试类:(使用底层的加载机制模拟情况)

public class Test {

    @org.junit.Test
    public void testXMLConfig() {
        XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring/spring.xml"));
        TestController controller = beanFactory.getBean(TestController.class);
        System.out.println(controller.testController());
    }
}

结果

覆盖初始化数据!!!

12)、init-method 和 destroy-method

作用:实例<bean>之前执行的方法,销毁<bean>之前执行的方法

测试:

测试Controller控制层

public class TestController {

    public String testController() {
        return "---- >>> 方法调用成功!!!";
    }

    // 实例<bean>之前执行
    public void init(){
        System.out.println("初始化方法!!!");
    }

    // 销毁<bean>之前执行
    public void destroy(){
        System.out.println("销毁方法!!!");
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean class="test.define.controller.TestController" init-method="init" destroy-method="destroy"/>
</beans>

测试类

public class Test {

    @org.junit.Test
    public void testXMLConfig() {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/spring.xml");
        TestController controller = context.getBean(TestController.class);
        System.out.println(controller.testController());
        context.close();
    }
}

结果

初始化方法!!!
---- >>> 方法调用成功!!!
销毁方法!!!

13)、factory-method

作用:静态工厂方法(当前类方法)

测试:

定义 Model

public class Model {  
  
    private String id;  
    private String name;  
  
    public Model(String id, String name) {  
        this.id = id;  
        this.name = name;  
    }  
  
    public String toString() {  
        return id + "-----" + name;  
    }  
}  

定义 ModelFactory

public class ModelFactory {  
  
    private static Map<Integer, Model> map = new HashMap<Integer, Model>();  
  
    static {  
        map.put(1, new Model("id1", "Honda"));  
        map.put(2, new Model("id2", "Audi"));  
        map.put(3, new Model("id3", "BMW"));  
    }  
  
    public static Model getModel(int id) {  
        return map.get(id);  
    }  
}  
配置文件
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
       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.xsd">  
      
    <!-- 静态工厂对象:注入别名 = getModelById,返回当前类的类型 = getModel 方法的返回类型 -->  
    <bean id="getModelById" class="test.define.model.ModelFactory" factory-method="getModel">  
        <constructor-arg value="1"/>  
    </bean>  
</beans> 

测试类

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = "classpath:spring/spring.xml")  
public class Test {  
  
    @Autowired  
    @Qualifier("getModelById")  
    private Model model;  
  
    @org.junit.Test  
    public void testXMLConfig() {  
        System.out.println(model);  
    }  
} 
结果

id1-----Honda

14)、factory-bean
作用:动态工厂方法(动态类:可注入)

测试:

测试 Model

public class Model {  
  
    private String id;  
    private String name;  
  
    public Model(String id, String name) {  
        this.id = id;  
        this.name = name;  
    }  
  
    public String toString() {  
        return id + "-----" + name;  
    }  
}  

测试初始化数据 InitModel(注入的类)

public class InitModel {  
  
    private Map<Integer, Model> map = new HashMap<Integer, Model>();  
  
    {  
        map.put(1, new Model("id1", "Honda"));  
        map.put(2, new Model("id2", "Audi"));  
        map.put(3, new Model("id3", "BMW"));  
    }  
  
    public Model getModelById(int id) {  
        return map.get(id);  
    }  
} 

测试 ModelFactory

public class ModelFactory {  
  
    @Autowired  
    private InitModel initModel;  
  
    public Model getModel(int id) {  
        return initModel.getModelById(id);  
    }  
}  

配置文件

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
       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.xsd">  
  
    <!-- 初始化数据 -->  
    <bean class="test.define.model.InitModel"/>  
  
    <!-- 普通类:简单的IoC类:包括自动注入、调用注入类的方法 -->  
    <bean id="initModel" class="test.define.model.ModelFactory"></bean>  
  
    <!-- 动态工厂对象:注入别名 = getModelById,返回<别名 = initModel 的 getModel 方法返回的类型> -->  
    <bean id="getModelById" factory-bean="initModel" factory-method="getModel">  
        <constructor-arg value="1"/>  
    </bean>  
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = "classpath:spring/spring.xml")  
public class Test {  
  
    @Autowired  
    @Qualifier("getModelById")  
    private Model model;  
  
    @org.junit.Test  
    public void testXMLConfig() {  
        System.out.println(model);  
    }  
} 

结果

id1-----Honda

2、<bean>元素

1)、<meta> 元素

作用:描述元素(key属性、value属性

测试:略


2)、<lookup-method> 元素

作用:一个单例 <bean> 中,引用了多例 <bean> 时使用(注意:是引用关系,不是单个<bean>使用)

测试:

定义 Service 服务接口

public interface TestService {

    String testService();
}

定义 Service 服务接口实现

public class ProServiceImpl implements TestService {

    private int i = 1;

    public String testService() {
        return i++ + "";
    }
}
public class TestServiceImpl implements TestService{

    private int i = 1;

    public String testService() {
        return i++ + "";
    }
}

定义 Controller 控制层

public abstract class TestController {

    // 动态实例:使用cglib动态代理实例赋值
    public abstract TestService getService();

    public String testController() {
        // 抽象调用
        return getService().testService();
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- 单例 -->
    <bean id="testService" class="test.define.service.impl.TestServiceImpl" scope="singleton" />
    <!-- 多例 -->
    <bean id="proService" class="test.define.service.impl.ProServiceImpl" scope="prototype"></bean>

    <!-- 测试单例注入 -->
    <bean id="testController1" class="test.define.controller.TestController" scope="singleton">
        <lookup-method name="getService" bean="testService"/>
    </bean>
    <!-- 测试多例注入 -->
    <bean id="testController2" class="test.define.controller.TestController" scope="singleton">
        <lookup-method name="getService" bean="proService"/>
    </bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    // 单例注入
    @Autowired
    @Qualifier("testController1")
    private TestController c1;

    // 多例注入
    @Autowired
    @Qualifier("testController2")
    private TestController c2;

    @org.junit.Test
    public void testXMLConfig() {
        // 单例测试
        System.out.println(c1.testController());
        System.out.println(c1.testController());
        System.out.println(c1.testController());
        System.out.println("-----------------");
        // 多例测试
        System.out.println(c2.testController());
        System.out.println(c2.testController());
        System.out.println(c2.testController());
    }
}

结果

1
2
3
-----------------
1
1
1


3)、<replaced-method> 元素

作用:替换一个正在运行的方法

测试:

定义被替换类

public class TestController {

    // 被替换的方法:方法名称 testController
    public String testController() {
        return "SUCCESS!!!";
    }
}

定义替换类

public class ReplaceController implements MethodReplacer {

    // 该方法表示替换任何一个方法
    // obj 返回值类型
    // method 被替换的方法
    // args 额外参数
    public Object reimplement(Object obj, Method method, Object[] args) throws Throwable {
        // 返回与被替换的方法相同的类型
        System.out.println(method.getName());
        return "Replace Controller: SUCCESS!!!";
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <!-- 替换其他方法的类:只有一个有效方法 reimplement,表示替换方法 -->
    <bean id="replaceController" class="test.define.replace.ReplaceController"/>

    <!-- 被替换方法的类 -->
    <bean id="testController" class="test.define.controller.TestController">
        <!-- name 表示被替换的方法名 -->
        <!-- replaceController 表示替换的方法 -->
        <replaced-method name="testController" replacer="replaceController">
            <!-- 替换方法的第一个参数 -->
            <arg-type>String</arg-type>
        </replaced-method>
    </bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    private TestController controller;

    @org.junit.Test
    public void testXMLConfig() {
        System.out.println(controller.testController());
    }
}

结果

testController
Replace Controller: SUCCESS!!!

4)、<constructor-arg> 元素

          index:索引赋值

          type:参数类型

          name:参数名称

          value:具体的值

分为三种:

基本类型注入

引用类型注入

集合类型注入

测试基本类型注入

测试注入类

public class TestController {

    private String str;

    public TestController() {
        str = "No params";
    }

    public TestController(int i) {
        str = "One param, type is int : " + i;
    }

    public TestController(String s) {
        str = "One param, type is string : " + s;
    }

    public TestController(int i, String s) {
        str = "Two param, type is int and string: " + i + ", " + s;
    }

    public void testController() {
        System.out.println(str);
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">


    <!-- 无参构造方法 -->
    <bean id="controllerNoParam" class="test.define.controller.TestController"/>

    <!-- 一个参数构造方法:默认注入(字符串) -->
    <bean id="attributeControllerOneParamWithString" class="test.define.controller.TestController">
        <constructor-arg value="默认方式赋值:默认字符串"/>
    </bean>

    <!-- 一个参数构造方法:根据类型注入 -->
    <bean id="attributeControllerOneParamWithInt" class="test.define.controller.TestController">
        <constructor-arg type="int" value="1"/>
    </bean>

    <!-- 一个参数构造方法:根据参数名注入 -->
    <bean id="attributeControllerOneParamWithStringAndName" class="test.define.controller.TestController">
        <constructor-arg value="参数名方式赋值" name="s"/>
    </bean>

    <!-- 两个参数构造方法:根据索引注入 -->
    <bean id="attributeControllerTwoParam" class="test.define.controller.TestController">
        <constructor-arg index="0" value="1"/>
        <constructor-arg index="1" value="两个参数构造方法"/>
    </bean>


    <!-- 一个参数构造方法:默认注入(字符串) -->
    <bean id="elementControllerOneParamWithString" class="test.define.controller.TestController">
        <constructor-arg>
            <value>默认方式赋值:默认字符串</value>
        </constructor-arg>
    </bean>

    <!-- 一个参数构造方法:根据类型注入 -->
    <bean id="elementControllerOneParamWithInt" class="test.define.controller.TestController">
        <constructor-arg>
            <value type="int">1</value>
        </constructor-arg>
    </bean>

    <!-- 一个参数构造方法:根据参数名注入 -->
    <bean id="elementControllerOneParamWithStringAndName" class="test.define.controller.TestController">
        <constructor-arg name="s">
            <value>参数名方式赋值</value>
        </constructor-arg>
    </bean>

    <!-- 两个参数构造方法:根据索引注入 -->
    <bean id="elementControllerTwoParam" class="test.define.controller.TestController">
        <constructor-arg index="0">
            <value>1</value>
        </constructor-arg>
        <constructor-arg index="1">
            <value>两个参数构造方法</value>
        </constructor-arg>
    </bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    /**
     * 无参构造方法
     */
    @Autowired
    @Qualifier("controllerNoParam")
    private TestController controllerNoParam;

    /**
     * 基本类型注入:属性注入
     */
    @Autowired
    @Qualifier("attributeControllerOneParamWithInt")
    private TestController attributeControllerOneParamWithInt;

    @Autowired
    @Qualifier("attributeControllerOneParamWithString")
    private TestController attributeControllerOneParamWithString;
    @Autowired
    @Qualifier("attributeControllerOneParamWithStringAndName")
    private TestController attributeControllerOneParamWithStringAndName;

    /**
     * 基本类型注入:元素注入
     */
    @Autowired
    @Qualifier("elementControllerTwoParam")
    private TestController elementControllerTwoParam;

    @Autowired
    @Qualifier("elementControllerOneParamWithInt")
    private TestController elementControllerOneParamWithInt;

    @Autowired
    @Qualifier("elementControllerOneParamWithString")
    private TestController elementControllerOneParamWithString;
    @Autowired
    @Qualifier("elementControllerOneParamWithStringAndName")
    private TestController elementControllerOneParamWithStringAndName;

    @Autowired
    @Qualifier("attributeControllerTwoParam")
    private TestController attributeControllerTwoParam;


    @org.junit.Test
    public void testXMLConfig() {
        /**
         * 无参构造方法
         */
        controllerNoParam.testController();
        /**
         * 基本类型注入:属性注入
         */
        // 1 个参数构造方法
        attributeControllerOneParamWithInt.testController();
        // 1 个参数构造方法
        attributeControllerOneParamWithString.testController();
        // 1 个参数构造方法
        attributeControllerOneParamWithStringAndName.testController();
        // 2 个参数构造方法
        attributeControllerTwoParam.testController();
        /**
         * 基本类型注入:元素注入
         */
        // 1 个参数构造方法
        elementControllerOneParamWithInt.testController();
        // 1 个参数构造方法
        elementControllerOneParamWithString.testController();
        // 1 个参数构造方法
        elementControllerOneParamWithStringAndName.testController();
        // 2 个参数构造方法
        elementControllerTwoParam.testController();
    }
}

结果

No params
One param, type is int : 1
One param, type is string : 默认方式赋值:默认字符串
One param, type is string : 参数名方式赋值
Two param, type is int and string: 1, 两个参数构造方法
One param, type is int : 1
One param, type is string : 默认方式赋值:默认字符串
One param, type is string : 参数名方式赋值
Two param, type is int and string: 1, 两个参数构造方法

测试引用类型注入

引用对象

public class Model {

    private String name;

    public Model(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

测试注入类

public class TestController {

    private String str;

    public TestController(int i, Model model) {
        str = "Two param, type is int : " + i + ", model : " + model;
    }

    public TestController(String s, Model model) {
        str = "Two param, type is string : " + s + ", model : " + model;
    }

    public void testController() {
        System.out.println(str);
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">
    
    <bean id="testModel" class="test.define.model.Model">
        <constructor-arg value="model 名称"/>
    </bean>

    <!-- 属性:类型注入 -->
    <bean id="attributeControllerWithIntAndRef" class="test.define.controller.TestController">
        <constructor-arg type="int" value="1"/>
        <constructor-arg type="test.define.model.Model" ref="testModel"/>
    </bean>

    <!-- 属性:参数名称注入 -->
    <bean id="attributeControllerWithStringAndRef" class="test.define.controller.TestController">
        <constructor-arg value="参数名方式赋值" name="s"/>
        <constructor-arg ref="testModel" name="model"/>
    </bean>

    <!-- 属性:索引注入 -->
    <bean id="attributeControllerWithIndex" class="test.define.controller.TestController">
        <constructor-arg index="0" value="1"/>
        <constructor-arg index="1" ref="testModel"/>
    </bean>



    <!-- 元素:类型注入 -->
    <bean id="elementControllerWithIntAndRef" class="test.define.controller.TestController">
        <constructor-arg>
            <value type="int">1</value>
        </constructor-arg>
        <constructor-arg>
            <ref bean="testModel"/>
        </constructor-arg>
    </bean>

    <!-- 元素:参数名称注入 -->
    <bean id="elementControllerWithStringAndRef" class="test.define.controller.TestController">
        <constructor-arg name="s">
            <value>参数名方式赋值</value>
        </constructor-arg>
        <constructor-arg name="model">
            <ref bean="testModel"/>
        </constructor-arg>
    </bean>

    <!-- 元素:索引注入 -->
    <bean id="elementControllerWithIndex" class="test.define.controller.TestController">
        <constructor-arg index="0">
            <value>1</value>
        </constructor-arg>
        <constructor-arg index="1">
            <ref bean="testModel"/>
        </constructor-arg>
    </bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    /**
     * 引用类型注入:属性注入
     */
    @Autowired
    @Qualifier("attributeControllerWithIntAndRef")
    private TestController attributeControllerWithIntAndRef;

    @Autowired
    @Qualifier("attributeControllerWithStringAndRef")
    private TestController attributeControllerWithStringAndRef;
    @Autowired
    @Qualifier("attributeControllerWithIndex")
    private TestController attributeControllerWithIndex;

    /**
     * 引用类型注入:元素注入
     */
    @Autowired
    @Qualifier("elementControllerWithIntAndRef")
    private TestController elementControllerWithIntAndRef;

    @Autowired
    @Qualifier("elementControllerWithStringAndRef")
    private TestController elementControllerWithStringAndRef;

    @Autowired
    @Qualifier("elementControllerWithIndex")
    private TestController elementControllerWithIndex;

    @org.junit.Test
    public void testXMLConfig() {
        /**
         * 基本类型注入:属性注入
         */
        attributeControllerWithIntAndRef.testController();
        attributeControllerWithStringAndRef.testController();
        attributeControllerWithIndex.testController();
        /**
         * 基本类型注入:元素注入
         */
        elementControllerWithIntAndRef.testController();
        elementControllerWithStringAndRef.testController();
        elementControllerWithIndex.testController();
    }
}

结果

Two param, type is int : 1, model : model 名称
Two param, type is string : 参数名方式赋值, model : model 名称
Two param, type is string : 1, model : model 名称
Two param, type is int : 1, model : model 名称
Two param, type is string : 参数名方式赋值, model : model 名称
Two param, type is string : 1, model : model 名称

测试集合类型注入

引用对象

public class Model {

    private String name;

    public Model(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

测试注入类

public class TestController {

    private String str;

    public TestController(int i, List<Integer> list) {
        str = i + "-----" + Arrays.toString(list.toArray());
    }

    public TestController(String s, List<Model> models) {
        str = s + "-----" + Arrays.toString(models.toArray());
    }

    public TestController(int i, Set<Integer> list) {
        str = i + "-----" + Arrays.toString(list.toArray());
    }

    public TestController(String s, Set<Model> models) {
        str = s + "-----" + Arrays.toString(models.toArray());
    }

    public TestController(int i, Map<Integer,String> map) {
        str = i + "-----" + Arrays.toString(map.entrySet().toArray());
    }

    public TestController(String s, Map<Integer,Model> modelMap) {
        str = s + "-----" + Arrays.toString(modelMap.entrySet().toArray());
    }

    public void testController() {
        System.out.println(str);
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean id="testModel" class="test.define.model.Model">
        <constructor-arg value="model 名称"/>
    </bean>

    <!-- List:类型注入 -->
    <bean id="list" class="test.define.controller.TestController">
        <constructor-arg type="int" value="1"/>
        <constructor-arg type="java.util.List">
            <list>
                <value type="int">1</value>
                <value type="int">2</value>
                <value type="int">3</value>
            </list>
        </constructor-arg>
    </bean>

    <!-- List:参数名称注入 -->
    <bean id="listAndRef" class="test.define.controller.TestController">
        <constructor-arg value="参数名方式赋值" name="s"/>
        <constructor-arg type="java.util.List">
            <list>
                <ref bean="testModel"/>
                <ref bean="testModel"/>
                <ref bean="testModel"/>
            </list>
        </constructor-arg>
    </bean>

    <!-- Set:索引注入 -->
    <bean id="set" class="test.define.controller.TestController">
        <constructor-arg index="0" value="1"/>
        <constructor-arg type="java.util.Set">
            <set>
                <value type="int">1</value>
                <value type="int">2</value>
                <value type="int">3</value>
            </set>
        </constructor-arg>
    </bean>

    <!-- Set:顺序注入 -->
    <bean id="setAndRef" class="test.define.controller.TestController">
        <constructor-arg>
            <value>参数名方式赋值</value>
        </constructor-arg>
        <constructor-arg type="java.util.Set">
            <set>
                <ref bean="testModel"/>
                <ref bean="testModel"/>
                <ref bean="testModel"/>
            </set>
        </constructor-arg>
    </bean>

    <!-- Map:参数名称注入 -->
    <bean id="map" class="test.define.controller.TestController">
        <constructor-arg  name="i">
            <value>1</value>
        </constructor-arg>
        <constructor-arg name="map">
            <map>
                <entry>
                    <key>
                        <value type="int">1</value>
                    </key>
                    <value type="java.lang.String">测试1</value>
                </entry>
                <entry>
                    <key>
                        <value type="int">2</value>
                    </key>
                    <value type="java.lang.String">测试2</value>
                </entry>
            </map>
        </constructor-arg>
    </bean>

    <!-- Map:索引注入 -->
    <bean id="mapAndRef" class="test.define.controller.TestController">
        <constructor-arg index="0">
            <value>1</value>
        </constructor-arg>
        <constructor-arg index="1">
            <map>
                <entry>
                    <key>
                        <value type="int">1</value>
                    </key>
                    <ref bean="testModel"/>
                </entry>
                <entry>
                    <key>
                        <value type="int">2</value>
                    </key>
                    <ref bean="testModel"/>
                </entry>
            </map>
        </constructor-arg>
    </bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    @Qualifier("list")
    private TestController list;

    @Autowired
    @Qualifier("listAndRef")
    private TestController listAndRef;
    @Autowired
    @Qualifier("set")
    private TestController set;

    @Autowired
    @Qualifier("setAndRef")
    private TestController setAndRef;

    @Autowired
    @Qualifier("map")
    private TestController map;

    @Autowired
    @Qualifier("mapAndRef")
    private TestController mapAndRef;

    @org.junit.Test
    public void testXMLConfig() {
        list.testController();
        listAndRef.testController();
        set.testController();
        setAndRef.testController();
        map.testController();
        mapAndRef.testController();
    }
}

结果

1-----[1, 2, 3]
参数名方式赋值-----[model 名称, model 名称, model 名称]
1-----[1, 2, 3]
参数名方式赋值-----[model 名称]
1-----[1=测试1, 2=测试2]
1-----[1=model 名称, 2=model 名称]


5)、<property> 元素

          name:属性名称

          type:属性类型  

          ref:引用类型

分为三种:

基本类型注入

引用类型注入

集合类型注入

测试基本类型注入

测试注入类

public class TestController {

    private String s;

    private int i;

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean id="testInt" class="test.define.controller.TestController">
        <property name="i" value="1"/>
    </bean>

    <bean id="testString" class="test.define.controller.TestController">
        <property name="s">
            <value type="java.lang.String">字符串注入</value>
        </property>
    </bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    @Qualifier("testInt")
    private TestController testInt;

    @Autowired
    @Qualifier("testString")
    private TestController testString;

    @org.junit.Test
    public void testXMLConfig() {
        // 整型注入
        System.out.println(testInt.getI());
        // 字符串注入
        System.out.println(testString.getS());
    }
}

结果

1
字符串注入

测试引用类型注入

引用对象

public class Model {

    private String name;

    public Model(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

测试注入类

public class TestController {

    private Model model;

    public Model getModel() {
        return model;
    }

    public void setModel(Model model) {
        this.model = model;
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean id="model" class="test.define.model.Model">
        <constructor-arg name="name" value="model名称测试"/>
    </bean>

    <bean id="attributeModel" class="test.define.controller.TestController">
        <property name="model" ref="model"/>
    </bean>

    <bean id="elementModel" class="test.define.controller.TestController">
        <property name="model">
            <ref bean="model"/>
        </property>
    </bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    @Qualifier("attributeModel")
    private TestController attributeModel;

    @Autowired
    @Qualifier("elementModel")
    private TestController elementModel;

    @org.junit.Test
    public void testXMLConfig() {
        System.out.println(attributeModel.getModel());
        System.out.println(elementModel.getModel());
    }
}

结果

model名称测试
model名称测试


测试集合类型注入

引用对象

public class Model {

    private String name;

    public Model(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

测试注入类

public class TestController {

    private List<Integer> list;
    private List<Model> modelList;

    private Set<String> set;
    private Set<Model> modelSet;

    private Map<Integer,String> map;
    private Map<Integer,Model> modelMap;

    public String getList() {
        return Arrays.toString(list.toArray());
    }

    public void setList(List<Integer> list) {
        this.list = list;
    }

    public String getModelList() {
        return Arrays.toString(modelList.toArray());
    }

    public void setModelList(List<Model> modelList) {
        this.modelList = modelList;
    }

    public String getSet() {
        return Arrays.toString(set.toArray());
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    public String getModelSet() {
        return Arrays.toString(modelSet.toArray());
    }

    public void setModelSet(Set<Model> modelSet) {
        this.modelSet = modelSet;
    }

    public String getMap() {
        return Arrays.toString(map.entrySet().toArray());
    }

    public void setMap(Map<Integer, String> map) {
        this.map = map;
    }

    public String getModelMap() {
        return Arrays.toString(modelMap.entrySet().toArray());
    }

    public void setModelMap(Map<Integer, Model> modelMap) {
        this.modelMap = modelMap;
    }
}

配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">

    <bean id="model" class="test.define.model.Model">
        <constructor-arg name="name" value="model名称测试"/>
    </bean>

    <bean id="list" class="test.define.controller.TestController">
        <property name="list">
            <list>
                <value>1</value>
                <value>2</value>
                <value>3</value>
            </list>
        </property>
    </bean>

    <bean id="modelList" class="test.define.controller.TestController">
        <property name="modelList">
            <list>
                <ref bean="model"/>
                <ref bean="model"/>
                <ref bean="model"/>
            </list>
        </property>
    </bean>

    <bean id="set" class="test.define.controller.TestController">
        <property name="set">
            <set>
                <value>1</value>
                <value>2</value>
                <value>3</value>
            </set>
        </property>
    </bean>

    <bean id="modelSet" class="test.define.controller.TestController">
        <property name="modelSet">
            <set>
                <ref bean="model"/>
                <ref bean="model"/>
                <ref bean="model"/>
            </set>
        </property>
    </bean>

    <bean id="map" class="test.define.controller.TestController">
        <property name="map">
            <map>
                <entry>
                    <key>
                        <value type="int">1</value>
                    </key>
                    <value>测试1</value>
                </entry>
                <entry>
                    <key>
                        <value type="int">2</value>
                    </key>
                    <value>测试2</value>
                </entry>
            </map>
        </property>
    </bean>

    <bean id="modelMap" class="test.define.controller.TestController">
        <property name="modelMap">
            <map>
                <entry>
                    <key>
                        <value type="int">1</value>
                    </key>
                    <ref bean="model"/>
                </entry>
                <entry>
                    <key>
                        <value type="int">2</value>
                    </key>
                    <ref bean="model"/>
                </entry>
            </map>
        </property>
    </bean>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {

    @Autowired
    @Qualifier("list")
    private TestController list;

    @Autowired
    @Qualifier("modelList")
    private TestController modelList;

    @Autowired
    @Qualifier("set")
    private TestController set;

    @Autowired
    @Qualifier("modelSet")
    private TestController modelSet;

    @Autowired
    @Qualifier("map")
    private TestController map;

    @Autowired
    @Qualifier("modelMap")
    private TestController modelMap;

    @org.junit.Test
    public void testXMLConfig() {
        System.out.println(list.getList());
        System.out.println(modelList.getModelList());
        System.out.println(set.getSet());
        System.out.println(modelSet.getModelSet());
        System.out.println(map.getMap());
        System.out.println(modelMap.getModelMap());
    }
}

结果

[1, 2, 3]
[model名称测试, model名称测试, model名称测试]
[1, 2, 3]
[model名称测试]
[1=测试1, 2=测试2]
[1=model名称测试, 2=model名称测试]


6)、<qualifier> 元素

作用:同@Qualifier直接

测试:略


7)、元素扩展

          util:工具:集合

              1、定义 Constant (常量

              2、定义 List

              3、定义 Set

              4、定义 Map

          c:命名空间:构造注入简化版

              1、基本类型注入

              2、引用类型注入

              3、集合类型注入

          p:命名空间:属性注入简化版

              1、基本类型注入

              2、引用类型注入

              3、集合类型注入


测试 util:命名空间

<?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:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="model" class="test.define.model.Model">
        <constructor-arg value="model测试名称"/>
    </bean>

    <!-- 定义常量 -->
    <util:constant id="default_encode" static-field="test.define.constant.Constants.DEFAULT_ENCODE"/>

    <!-- 定义 List -->
    <util:list id="list">
        <value>1</value>
        <value>2</value>
        <value>3</value>
    </util:list>

    <!-- 定义 List -->
    <util:list id="modelList">
        <ref bean="model"/>
        <ref bean="model"/>
        <ref bean="model"/>
    </util:list>

    <!-- 定义 Set -->
    <util:set id="set">
        <value>1</value>
        <value>2</value>
        <value>3</value>
    </util:set>

    <!-- 定义 Set -->
    <util:set id="modelSet">
        <ref bean="model"/>
        <ref bean="model"/>
        <ref bean="model"/>
    </util:set>

    <!-- 定义 Map -->
    <util:map id="map">
        <entry>
            <key>
                <value>1</value>
            </key>
            <value>测试1</value>
        </entry>
        <entry>
            <key>
                <value>2</value>
            </key>
            <value>测试2</value>
        </entry>
    </util:map>

    <!-- 定义 Map -->
    <util:map id="modelMap">
        <entry>
            <key>
                <value>1</value>
            </key>
            <ref bean="model"/>
        </entry>
        <entry>
            <key>
                <value>2</value>
            </key>
            <ref bean="model"/>
        </entry>
    </util:map>
</beans>


测试 c:命名空间(基本类型注入)

测试 c:命名空间(引用类型注入)

测试 c:命名空间(集合类型注入)

引用对象

public class Model {

    private String name;

    public Model(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

定义测试Controller

public class TestController {

    private String str;

    // 基本类型
    public TestController(String name, int age) {
        str = name + "-----" + age;
    }

    // 引用类型
    public TestController(Model model) {
        str = model.toString();
    }

    // 集合类型
    public TestController(List<Integer> list, List<Model> modelList,
                          Set<Integer> set, Set<Model> modelSet,
                          Map<Integer, String> map, Map<Integer, Model> modelMap) {
        str = Arrays.toString(list.toArray()) + "\n" +
                Arrays.toString(modelList.toArray()) + "\n" +
                Arrays.toString(set.toArray()) + "\n" +
                Arrays.toString(modelSet.toArray()) + "\n" +
                Arrays.toString(map.entrySet().toArray()) + "\n" +
                Arrays.toString(modelMap.entrySet().toArray());
    }

    public String testController() {
        return str;
    }
}

配置文件

<?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:util="http://www.springframework.org/schema/util"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util
       http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 属性赋值:基本类型赋值 -->
    <bean id="attributeProperty" class="test.define.controller.TestController" c:name="张三" c:age="18"/>

    <!-- 属性赋值:引用类型赋值 -->
    <bean id="attributeRef" class="test.define.controller.TestController" c:model-ref="model"/>

    <!-- 属性赋值:集合类型赋值 -->
    <bean id="attributeCollection" class="test.define.controller.TestController" c:list-ref="list"
          c:modelList-ref="modelList" c:set-ref="set"
          c:modelSet-ref="modelSet"
          c:map-ref="map" c:modelMap-ref="modelMap"/>

    <!-- 索引赋值:基本类型赋值 -->
    <bean id="indexProperty" class="test.define.controller.TestController" c:_0="张三" c:_1="18"/>

    <!-- 索引赋值:引用类型赋值 -->
    <bean id="indexRef" class="test.define.controller.TestController" c:_0-ref="model"/>

    <!-- 索引赋值:集合类型赋值 -->
    <bean id="indexCollection" class="test.define.controller.TestController" c:_0-ref="list" c:_1-ref="modelList"
          c:set-ref="set"
          c:modelSet-ref="modelSet"
          c:map-ref="map" c:modelMap-ref="modelMap"/>


    <!-- ############################################################################################### -->
    <bean id="model" class="test.define.model.Model">
        <constructor-arg value="model测试名称"/>
    </bean>

    <!-- 定义常量 -->
    <util:constant id="default_encode" static-field="test.define.constant.Constants.DEFAULT_ENCODE"/>

    <!-- 定义 List -->
    <util:list id="list">
        <value>1</value>
        <value>2</value>
        <value>3</value>
    </util:list>

    <!-- 定义 List -->
    <util:list id="modelList">
        <ref bean="model"/>
        <ref bean="model"/>
        <ref bean="model"/>
    </util:list>

    <!-- 定义 Set -->
    <util:set id="set">
        <value>1</value>
        <value>2</value>
        <value>3</value>
    </util:set>

    <!-- 定义 Set -->
    <util:set id="modelSet">
        <ref bean="model"/>
        <ref bean="model"/>
        <ref bean="model"/>
    </util:set>

    <!-- 定义 Map -->
    <util:map id="map">
        <entry>
            <key>
                <value>1</value>
            </key>
            <value>测试1</value>
        </entry>
        <entry>
            <key>
                <value>2</value>
            </key>
            <value>测试2</value>
        </entry>
    </util:map>

    <!-- 定义 Map -->
    <util:map id="modelMap">
        <entry>
            <key>
                <value>1</value>
            </key>
            <ref bean="model"/>
        </entry>
        <entry>
            <key>
                <value>2</value>
            </key>
            <ref bean="model"/>
        </entry>
    </util:map>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {
    /**
     * 属性赋值
     */
    @Autowired
    @Qualifier("attributeProperty")
    private TestController attributeProperty;

    @Autowired
    @Qualifier("attributeRef")
    private TestController attributeRef;

    @Autowired
    @Qualifier("attributeCollection")
    private TestController attributeCollection;

    /**
     * 索引赋值
     */
    @Autowired
    @Qualifier("indexProperty")
    private TestController indexProperty;

    @Autowired
    @Qualifier("indexRef")
    private TestController indexRef;

    @Autowired
    @Qualifier("indexCollection")
    private TestController indexCollection;

    @org.junit.Test
    public void testXMLConfig() {
        // 属性赋值
        System.out.println(attributeProperty.testController());
        System.out.println(attributeRef.testController());
        System.out.println(attributeCollection.testController());
        // 索引赋值
        System.out.println(indexProperty.testController());
        System.out.println(indexRef.testController());
        System.out.println(indexCollection.testController());
    }
}

结果

张三-----18
model测试名称
[1, 2, 3]
[model测试名称, model测试名称, model测试名称]
[1, 2, 3]
[model测试名称]
[1=测试1, 2=测试2]
[1=model测试名称, 2=model测试名称]
default_encode-----18
model测试名称
[1, 2, 3]
[model测试名称, model测试名称, model测试名称]
[1, 2, 3]
[model测试名称]
[1=测试1, 2=测试2]
[1=model测试名称, 2=model测试名称]


测试 p:命名空间(基本类型注入)

测试 p:命名空间(引用类型注入)

测试 p:命名空间(集合类型注入)

引用对象

public class Model {

    private String name;

    public Model(String name) {
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

测试Controller

public class TestController {

    // 基本类型
    private String name;
    private int age;
    // 引用类型
    private Model model;
    // 集合类型
    List<Integer> list;
    List<Model> modelList;
    Set<Integer> set;
    Set<Model> modelSet;
    Map<Integer, String> map;
    Map<Integer, Model> modelMap;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public void setModel(Model model) {
        this.model = model;
    }

    public void setList(List<Integer> list) {
        this.list = list;
    }

    public void setModelList(List<Model> modelList) {
        this.modelList = modelList;
    }

    public void setSet(Set<Integer> set) {
        this.set = set;
    }

    public void setModelSet(Set<Model> modelSet) {
        this.modelSet = modelSet;
    }

    public void setMap(Map<Integer, String> map) {
        this.map = map;
    }

    public void setModelMap(Map<Integer, Model> modelMap) {
        this.modelMap = modelMap;
    }

    public String getProperty() {
        return name + "-----" + age;
    }

    public String getRef() {
        return model.toString();
    }

    public String getCollection() {
        return Arrays.toString(list.toArray()) + "\n" +
                Arrays.toString(modelList.toArray()) + "\n" +
                Arrays.toString(set.toArray()) + "\n" +
                Arrays.toString(modelSet.toArray()) + "\n" +
                Arrays.toString(map.entrySet().toArray()) + "\n" +
                Arrays.toString(modelMap.entrySet().toArray());
    }
}

配置文件

<?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:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util
       http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 基本类型赋值 -->
    <bean id="propertyProperty" class="test.define.controller.TestController" p:name="张三" p:age="18"/>

    <!-- 引用类型赋值 -->
    <bean id="propertyRef" class="test.define.controller.TestController" p:model-ref="model"/>

    <!-- 集合类型赋值 -->
    <bean id="propertyCollection" class="test.define.controller.TestController" p:list-ref="list"
          p:modelList-ref="modelList" p:set-ref="set"
          p:modelSet-ref="modelSet"
          p:map-ref="map" p:modelMap-ref="modelMap"/>

    <!-- ############################################################################################### -->
    <bean id="model" class="test.define.model.Model">
        <constructor-arg value="model测试名称"/>
    </bean>

    <!-- 定义常量 -->
    <util:constant id="default_encode" static-field="test.define.constant.Constants.DEFAULT_ENCODE"/>

    <!-- 定义 List -->
    <util:list id="list">
        <value>1</value>
        <value>2</value>
        <value>3</value>
    </util:list>

    <!-- 定义 List -->
    <util:list id="modelList">
        <ref bean="model"/>
        <ref bean="model"/>
        <ref bean="model"/>
    </util:list>

    <!-- 定义 Set -->
    <util:set id="set">
        <value>1</value>
        <value>2</value>
        <value>3</value>
    </util:set>

    <!-- 定义 Set -->
    <util:set id="modelSet">
        <ref bean="model"/>
        <ref bean="model"/>
        <ref bean="model"/>
    </util:set>

    <!-- 定义 Map -->
    <util:map id="map">
        <entry>
            <key>
                <value>1</value>
            </key>
            <value>测试1</value>
        </entry>
        <entry>
            <key>
                <value>2</value>
            </key>
            <value>测试2</value>
        </entry>
    </util:map>

    <!-- 定义 Map -->
    <util:map id="modelMap">
        <entry>
            <key>
                <value>1</value>
            </key>
            <ref bean="model"/>
        </entry>
        <entry>
            <key>
                <value>2</value>
            </key>
            <ref bean="model"/>
        </entry>
    </util:map>
</beans>

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring.xml")
public class Test {
    @Autowired
    @Qualifier("propertyProperty")
    private TestController propertyProperty;

    @Autowired
    @Qualifier("propertyRef")
    private TestController propertyRef;

    @Autowired
    @Qualifier("propertyCollection")
    private TestController propertyCollection;

    @org.junit.Test
    public void testXMLConfig() {
        System.out.println(propertyProperty.getProperty());
        System.out.println(propertyRef.getRef());
        System.out.println(propertyCollection.getCollection());
    }
}

结果

张三-----18
model测试名称
[1, 2, 3]
[model测试名称, model测试名称, model测试名称]
[1, 2, 3]
[model测试名称]
[1=测试1, 2=测试2]
[1=model测试名称, 2=model测试名称]


<think>我们正在讨论Spring XML配置中的<beans>元素。根据引用[1]和[3],Spring的核心是提供组件之间的依赖注入和配置管理,而XML配置是传统的方式(尽管现在更推荐使用Java配置,如引用[2]所示)。在XML配置中,<beans>元素是整个配置文件的根元素。 ### <beans>元素的结构 在Spring XML配置文件中,<beans>是根元素,其基本结构如下: ```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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 在这里配置一个或多个<bean> --> <bean id="..." class="..."> <!-- 配置bean的属性和依赖 --> </bean> <!-- 启用注解驱动 --> <context:annotation-config/> </beans> ``` #### 关键属性说明: 1. **xmlns**:定义默认命名空间,通常是Spring Beans的命名空间(`http://www.springframework.org/schema/beans`)。 2. **xmlns:xsi**:定义XML Schema实例的命名空间,用于指定schemaLocation。 3. **xmlns:context**:引入其他命名空间(如context),用于使用特定于模块的配置(例如注解驱动)。 4. **xsi:schemaLocation**:指定命名空间对应的XML Schema定义文件的位置,这样XML解析器可以验证配置的正确性。 ### <beans>元素的使用 1. **配置Bean**:在<beans>内部可以定义多个<bean>元素,每个<bean>代表一个由Spring容器管理的对象。 ```xml <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mydb"/> <property name="username" value="root"/> <property name="password" value="password"/> </bean> ``` 2. **使用命名空间简化配置**:通过引入额外的命名空间(如`context`、`aop`、`tx`等),可以使用更简洁的标签来配置常见功能。 ```xml <!-- 启用组件扫描 --> <context:component-scan base-package="com.example"/> <!-- 启用事务管理 --> <tx:annotation-driven/> ``` 3. **配置Bean的作用域**:通过`scope`属性指定Bean的作用域(如singleton、prototype等)。 ```xml <bean id="myBean" class="com.example.MyBean" scope="prototype"/> ``` 4. **配置初始化/销毁方法**:使用`init-method`和`destroy-method`属性。 ```xml <bean id="lifecycleBean" class="com.example.LifecycleBean" init-method="init" destroy-method="cleanup"/> ``` ### 引用[3]的说明 引用[3]提到,使用XML Schema允许通过属性(attributes)而不是子元素(subelements)来配置属性值。例如: ```xml <bean id="myDataSource" class="com.example.DataSource" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/mydb" p:username="root" p:password="password"/> ``` 这里使用了`p:`命名空间(需在根元素声明`xmlns:p="http://www.springframework.org/schema/p"`),它允许直接使用属性设置,而不需要嵌套<property>元素。这种方式更简洁,但功能与嵌套<property>元素相同。 ### 总结 <beans>元素是Spring XML配置的根容器,它定义了配置的命名空间和验证规则,并包含多个<bean>定义。通过使用不同的命名空间,可以简化配置并启用高级特性。尽管现在推荐使用基于Java的配置(如引用[2]所示),但理解XML配置对于维护旧项目仍然很重要[^1][^2][^3]。 §§相关问题§§ 1. Spring XML配置与Java配置相比有什么优缺点? 2. 如何在Spring XML配置中实现AOP(面向切面编程)? 3. 如何管理Spring XML配置中的Bean作用域?</think>### Spring XML配置中`<beans>`元素的结构与用法详解 `<beans>`是Spring XML配置文件的根元素,用于定义Spring IoC容器的核心配置框架。其结构和用法如下: #### 一、基本结构 ```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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- Bean定义区域 --> </beans> ``` #### 二、关键组成部分 1. **命名空间声明**: - `xmlns`:定义默认命名空间(核心Bean命名空间) - `xmlns:xsi`:XML Schema实例命名空间 - `xmlns:context`:扩展命名空间(如事务、AOP等) - `xsi:schemaLocation`:关联XSD验证文件 2. **Bean定义**: ```xml <bean id="dataSource" class="com.example.DataSource" init-method="init" destroy-method="cleanup"> <property name="url" value="jdbc:mysql://localhost/db"/> <constructor-arg ref="configLoader"/> </bean> ``` - `id`:Bean的唯一标识符 - `class`:完全限定类名 - 生命周期方法:`init-method`/`destroy-method` - 依赖注入:`<property>`(设值注入)和`<constructor-arg>`(构造注入) 3. **作用域配置**: ```xml <bean id="sessionBean" class="com.example.SessionService" scope="session"/> ``` 支持的作用域:`singleton`(默认), `prototype`, `request`, `session`, `application` #### 三、高级功能 1. **自动装配**: ```xml <beans default-autowire="byType"> <bean id="service" class="com.example.ServiceImpl" autowire="constructor"/> </beans> ``` 模式:`no`(默认), `byName`, `byType`, `constructor` 2. **Profile配置**: ```xml <beans profile="production"> <bean id="dataSource" class="com.example.ProdDataSource"/> </beans> ``` 3. **属性占位符**: ```xml <context:property-placeholder location="classpath:app.properties"/> <bean id="dbConfig" class="com.example.DbConfig"> <property name="username" value="${db.user}"/> </bean> ``` #### 四、最佳实践 1. **模块化配置**: ```xml <import resource="database-config.xml"/> <import resource="security-config.xml"/> ``` 2. **混合配置模式**(XML+注解): ```xml <context:component-scan base-package="com.example"/> <context:annotation-config/> ``` 3. **简洁属性配置**(引用[3]): ```xml <!-- 使用p-namespace简化属性注入 --> <bean id="userService" class="com.example.UserService" p:dao-ref="userDao" p:timeout="5000"/> ``` #### 五、设计哲学 Spring的XML配置核心是将**组件依赖关系**与**业务逻辑**解耦(引用[1]): - 业务组件专注于功能实现 - 容器负责依赖注入和生命周期管理 - 支持通过配置切换实现类(如测试/生产环境) > **对比注解配置**:XML更适合集中管理跨组件配置,而`@Configuration`更适合模块化配置(引用[2])[^1][^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值