- 依赖对象的构造方法注入
Address.java
此类包含三个属性, 一个构造函数和toString()方法以返回这些对象的值。
package com.srcmini;
public class Address {
private String city;
private String state;
private String country;
public Address(String city, String state, String country) {
super();
this.city = city;
this.state = state;
this.country = country;
}public String toString(){
return city+" "+state+" "+country;
}
}
Employee.java
它包含三个属性id, name和address(从属对象), 两个构造函数和show()方法, 以显示当前对象(包括依赖对象)的记录。
package com.srcmini;
public class Employee {
private int id;
private String name;
private Address address;
//Aggregationpublic Employee() {System.out.println("def cons");
}public Employee(int id, String name, Address address) {
super();
this.id = id;
this.name = name;
this.address = address;
}void show(){
System.out.println(id+" "+name);
System.out.println(address.toString());
}}
applicationContext.xml
ref属性用于定义另一个对象的引用, 以这种方式我们将依赖对象作为构造函数参数传递。
<
?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<
bean id="a1" class="com.srcmini.Address">
<
constructor-arg value="http://www.srcmini.com/ghaziabad">
<
/constructor-arg>
<
constructor-arg value="http://www.srcmini.com/UP">
<
/constructor-arg>
<
constructor-arg value="http://www.srcmini.com/India">
<
/constructor-arg>
<
/bean>
<
bean id="e" class="com.srcmini.Employee">
<
constructor-arg value="http://www.srcmini.com/12" type="int">
<
/constructor-arg>
<
constructor-arg value="http://www.srcmini.com/Sonoo">
<
/constructor-arg>
<
constructor-arg>
<
ref bean="a1"/>
<
/constructor-arg>
<
/bean>
<
/beans>
Test.java
此类从applicationContext.xml文件获取Bean并调用show方法。
package com.srcmini;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
public class Test {
public static void main(String[] args) {Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
下载此示例(使用MyEclipse IDE开发)
【Spring依赖对象的构造函数注入实例】下载此示例(使用Eclipse IDE开发)
推荐阅读
- Spring带有Map构造函数注入示例
- Spring带有集合的构造函数注入示例
- Eclipse IDE创建Spring应用程序详细步骤实例
- Spring IoC容器基本内容介绍
- Spring的依赖注入是什么(答案都在这里——)
- Myeclipse中的Spring应用示例详解
- Spring教程入门介绍
- 应用出错,本文教您怎样处理explorer.exe应用程序出错
- 无法访问,本文教您怎样处理windows无法访问指定设备路径或文件