- 有依赖对象的Setter注入
Address.java
此类包含四个属性, 即setter和getter以及toString()方法。
package com.srcmini;
public class Address {
private String addressLine1, city, state, country;
//getters and setterspublic String toString(){
return addressLine1+" "+city+" "+state+" "+country;
}
【Spring带有依赖对象的Setter注入示例】Employee.java
它包含三个属性id, name和address(相关对象), 带有setInfo和getter的displayInfo()方法。
package com.srcmini;
public class Employee {
private int id;
private String name;
private Address address;
//setters and gettersvoid displayInfo(){
System.out.println(id+" "+name);
System.out.println(address);
}
}
applicationContext.xml
属性元素的ref属性用于定义另一个bean的引用。
<
?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="address1" class="com.srcmini.Address">
<
property name="addressLine1" value="http://www.srcmini.com/51, Lohianagar">
<
/property>
<
property name="city" value="http://www.srcmini.com/Ghaziabad">
<
/property>
<
property name="state" value="http://www.srcmini.com/UP">
<
/property>
<
property name="country" value="http://www.srcmini.com/India">
<
/property>
<
/bean>
<
bean id="obj" class="com.srcmini.Employee">
<
property name="id" value="http://www.srcmini.com/1">
<
/property>
<
property name="name" value="http://www.srcmini.com/Sachin Yadav">
<
/property>
<
property name="address" ref="address1">
<
/property>
<
/bean>
<
/beans>
Test.java
此类从applicationContext.xml文件获取Bean, 然后调用displayInfo()方法。
package com.srcmini;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee e=(Employee)factory.getBean("obj");
e.displayInfo();
}
}
下载此示例(使用MyEclipse IDE开发)
下载此示例(使用Eclipse IDE开发)
推荐阅读
- Spring带有Map的Setter进行注入示例
- Spring Setter对集合进行依赖注入示例
- 构造函数和setter注入之间有什么区别()
- Spring通过setter方法进行依赖注入示例
- Spring如何继承Bean(详细示例)
- 具有非字符串Map(具有从属对象)的构造函数注入示例
- Android_(游戏)打飞机02(游戏背景滚动)
- APP微信登录---第三方登录
- Android 7.0 新特性