带参数构造器的实体类 User.java:
package com.spring.demo;
/**
* 实体类 javabean
*/
public class User {
private int id;
private String name;
public User(int id, String name) {
System.out.println("User 对象创建:有参构造");
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
配置文件 bean.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:p="http://www.springframework.org/schema/p"
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 id="user" class="com.spring.demo.User">
<!--
指定有参构造的 参数:
value:参数值
index:参数索引,0表示第一个参数,1表示第二个参数
type:参数的类型
ref:引用外部的对象数据
-->
<constructor-arg value="22" index="0" type="int"/>
<constructor-arg value="张三" index="1" type="java.lang.String"/>
</bean>
</beans>
测试程序 Demo.java:
public class Demo {
@Test
public void test1() {
// 创建 IOC 容器
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
// 从 IOC 容器中获取 对象
User user = (User) context.getBean("user");
System.out.println(user);
}
}
输出结果:
配置 <constructor-arg> 节点的时候有一个属性 ref,表示引用外部的对象。
修改 bean.xml 如下:
再次运行测试程序 结果为: