前言:
-
Spring容器创建bean对象,一般通过反射机制查找bean元素的class属性值来找到要实例化的类,从而实例化bean对象。这便是调用构造方法来实例化bean对象
-
在某些情况下,若采用简单的xml配置文件方式,比如写大量的bean元素,会大大增加工作量。Spring容器还添加了一些bean元素的属性来减少配置文件的编写工作量。比如,静态工厂方法(factory-method属性)、实例化工厂方法(factory-bean属性、factory-method属性)
-
此外,Spring还提供了FactoryBean接口来支持开发人员自定义实例化bean对象的方式
案例源码:码云仓库的base-003子项目
1、调用构造方法创建bean对象
-
解释:
- 调用类的构造方法获取对应的bean实例
- 在配置文件中,只需设置好bean元素的class属性,Spring容器会自动调用构造方法来创建bean对象
-
基本格式:
<bean id="bean名称" name="bean名称或者别名" class="完整类路径"> <constructor-arg index="0" value="bean的值" ref="引用的bean名称" /> <constructor-arg index="1" value="bean的值" ref="引用的bean名称" /> .... </bean>
- constructor-arg:用于指定构造方法参数的值
- index:构造方法中参数的位置,从0开始,依次递增
- value:
- 给构造参数设置值,值的类型只能为简单类型,如byte,int,long,float,double,boolean,Byte,Long,Float,Double,枚举等;
- Spring容器在注入属性时,会自动将value值转换为对应的类型
- ref:当插入的值为容器内其他bean的时候,这个值为容器中对应bean的名称
- 若
不指定constructor-arg
,则Spring容器会调用默认无参构造方法
来创建bean对象;若指定constructor-arg
,则调用有参构造方法
来创建bean对象 - 若
指定constructor-arg
,index要和实体类的属性一一对应,不可缺少
- constructor-arg:用于指定构造方法参数的值
-
案例
-
实体类
package com.spring.study; public class Dog { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Dog() { this.name = "小白"; this.age = 1; } public Dog(String name, int age) { this.name = name; this.age = 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对象--> <bean id="dog1" class="com.spring.study.Dog"/> <!-- 调用有参构造方法创建bean对象--> <bean id="dog2" class="com.spring.study.Dog"> <constructor-arg index="0" value="大黄"/> <constructor-arg index="1" value="2"/> </bean> </beans>
-
测试类
package com.spring.test; import com.spring.study.Dog; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestConstructor { public static void main(String[] args) { // 1、定义bean配置文件位置 String classPathXml = "classpath:applicationContext.xml"; // 2、创建ClassPathXmlApplicationContext容器,给容器指定需要加载的bean配置文件 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(classPathXml); // 3、获取容器中所有bean对象 //获取所有bean对象的bean名称 String[] beanNames = context.getBeanDefinitionNames(); //打印输出bean对象 for (String beanName : beanNames){
-