Spring DI(依赖注入)之setter注入

Spring主要有两种注入方式:Setter注入和构造器注入。

使用Setter注入,可以注入很多类型。

(1) 注入基本类型:

可以使用Setter注入基本类型,如int、boolean等等,同时他们对应的封装类型,如Integer、Boolean等类型。

Company类定义如下:

package org.shirdrn.entity;

public class Company {
private int id;
private String name;
private Boolean chinese;
public Boolean getChinese() {
return chinese;
}
public void setChinese(Boolean chinese) {
this.chinese = chinese;
}
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;
}
}

对应的XML配置applicationContext.xml内容如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="companyBean" class="org.shirdrn.entity.Company"
abstract="false" singleton="true" lazy-init="default"
autowire="default" dependency-check="default">
<property name="id">
<value>2008</value>
</property>
<property name="name">
<value>CNAET</value>
</property>
<property name="chinese">
<value>true</value>
</property>
</bean>
</beans>

测试的程序代码如下:

package org.shirdrn.main;

import org.shirdrn.entity.Company;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Main {
public static void main(String[] args){
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Company c = (Company)ctx.getBean("companyBean");
System.out.println("id = "+c.getId());
System.out.println("name = "+c.getName());
System.out.println("isChinese = "+c.getChinese());

}
}

测试输出结果如下所示:

id = 2008
name = CNAET
isChinese = true

(2) 注入引用类型

在Company类中添加一个属性,公司的CEO:

private Person CEO;

并且添加它的Setter和Getter方法。

Person类如下所示:

package org.shirdrn.entity;

public class Person {
private Integer id;
private String name;
private Integer age;
private String email;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

对应的XML文件applicationContext.xml配置如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="person" class="org.shirdrn.entity.Person" abstract="false"
singleton="true" lazy-init="default" autowire="default"
dependency-check="default">
<property name="id">
<value>1001</value>
</property>
<property name="name">
<value>Shirdrn</value>
</property>
<property name="age">
<value>26</value>
</property>
<property name="email">
<value>shirdrn@hotmail.com</value>
</property>
</bean>

<bean id="companyBean" class="org.shirdrn.entity.Company"
abstract="false" singleton="true" lazy-init="default"
autowire="default" dependency-check="default">
<property name="id">
<value>2008</value>
</property>
<property name="name">
<value>CNAET</value>
</property>
<property name="chinese">
<value>true</value>
</property>
<property name="CEO">
<ref bean="person" />
</property>
</bean>

</beans>

第一个bean元素配置person,第二个bean配置了companyBean,公司的详情,其中CEO引用了第一个bean,表示一个人的详细信息,关键的配置在于:

<property name="CEO">
<ref bean="person" />
</property>

ref元素指定了引用的bean的id。

测试的程序代码如下:

package org.shirdrn.main;

import org.shirdrn.entity.Company;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Main {
public static void main(String[] args){
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Company c = (Company)ctx.getBean("companyBean");
System.out.println("company's id = "+c.getId());
System.out.println("company's name = "+c.getName());
System.out.println("company is Chinese = "+c.getChinese());
System.out.println("--- the following is CEO's detail ---");
System.out.println("CEO's id = "+c.getCEO().getId());
System.out.println("CEO's name = "+c.getCEO().getName());
System.out.println("CEO's age = "+c.getCEO().getAge());
System.out.println("CEO's Email = "+c.getCEO().getEmail());
}
}

测试输出结果如下所示:

company's id = 2008
company's name = CNAET
company is Chinese = true
--- the following is CEO's detail ---
CEO's id = 1001
CEO's name = Shirdrn
CEO's age = 26
CEO's Email = shirdrn@hotmail.com

(3) 注入Properties:

Properties类型也是键值对,而且它的键、值都只能是String类型。

新建一个PropertiesBean类,如下所示:

package org.shirdrn.entity;

import java.util.Properties;

public class PropertiesBean {
Properties hibernate;

public Properties getHibernate() {
return hibernate;
}

public void setHibernate(Properties hibernate) {
this.hibernate = hibernate;
}
}

XML中配置详情如下:

<bean id="propertiesBean" class="org.shirdrn.entity.PropertiesBean"
abstract="false" singleton="true" lazy-init="default"
autowire="default" dependency-check="default">
<property name="hibernate">
<props>
<prop key="connection.url">
jdbc:microsoft:sqlserver://localhost:1433;databasename=person
</prop>
<prop key="dialect">
org.hibernate.dialect.SQLServerDialect
</prop>
<prop key="connection.username">sa</prop>
<prop key="connection.password">111111</prop>
<prop key="show_sql">true</prop>
</props>
</property>
</bean>

测试程序代码如下:

package org.shirdrn.main;

import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import org.shirdrn.entity.PropertiesBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class Main {
public static void main(String[] args){
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
PropertiesBean propertiesBean = (PropertiesBean)ctx.getBean("propertiesBean");
Properties hibernate = propertiesBean.getHibernate();
Set keySet = hibernate.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
String propKey = (String)it.next();
String value = (String)hibernate.get(propKey);
System.out.println(propKey+" : "+value);
}
}
}

测试输出结果如下:

connection.url : jdbc:microsoft:sqlserver://localhost:1433;databasename=person
connection.username : sa
dialect : org.hibernate.dialect.SQLServerDialect
show_sql : true
connection.password : 111111
(4) 注入集合类型:

集合类型主要包括:List、Set、Map。

<1> 注入List

在Company类中再增加一个属性:

private List employees;

同时添加对应的Setter和Getter方法。

添加两个bean,他们的id分别为person1Bean和person2Bean:

<bean id="person1Bean" class="org.shirdrn.entity.Person" abstract="false"
singleton="true" lazy-init="default" autowire="default"
dependency-check="default">
<property name="id">
<value>2001</value>
</property>
<property name="name">
<value>张飞</value>
</property>
<property name="age">
<value>26</value>
</property>
<property name="email">
<value>zhangfei@live.cn</value>
</property>
</bean>

<bean id="person2Bean" class="org.shirdrn.entity.Person" abstract="false"
singleton="true" lazy-init="default" autowire="default"
dependency-check="default">
<property name="id">
<value>2002</value>
</property>
<property name="name">
<value>John Allen Green</value>
</property>
<property name="age">
<value>28</value>
</property>
<property name="email">
<value>john@baidu.com</value>
</property>
</bean>

在applicationContext.xml中的id为companyBean的bean中添加属性employees,使用list元素,并且list中是引用类型,分别指向person1Bean和person2Bean:

<property name="employees">
<list>
<ref bean="person1Bean" />
<ref bean="person2Bean" />
</list>
</property>

测试的程序代码如下:

package org.shirdrn.main;

import java.util.List;

import org.shirdrn.entity.Company;
import org.shirdrn.entity.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Main {
public static void main(String[] args){
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Company c = (Company)ctx.getBean("companyBean");
List employees = (List)c.getEmployees();
Person employee1 = (Person)employees.get(0);
Person employee2 = (Person)employees.get(1);
System.out.println("--- the following is Employee1's detail---");
System.out.println("employee1's id = "+employee1.getId());
System.out.println("employee1's name = "+employee1.getName());
System.out.println("employee1's age = "+employee1.getAge());
System.out.println("employee1's Email = "+employee1.getEmail());
System.out.println("\n--- the following is Employee2's detail---");
System.out.println("employee2's id = "+employee2.getId());
System.out.println("employee2's name = "+employee2.getName());
System.out.println("employee2's age = "+employee2.getAge());
System.out.println("employee2's Email = "+employee2.getEmail());
}
}

测试输出结果如下所示:

--- the following is Employee1's detail---
employee1's id = 2001
employee1's name = 张飞
employee1's age = 26
employee1's Email = zhangfei@live.cn

--- the following is Employee2's detail---
employee2's id = 2002
employee2's name = John Allen Green
employee2's age = 28
employee2's Email = john@baidu.com

<2> 注入Set

和注入List很相似,但是有细微的差别:

在配置bean元素的时候,在property元素内部使用set元素,同时set元素中可以使用value或ref节点;

Set集合中不允许存在重复的元素;

<3> 注入Map

由于Map存在键-值映射,所以配置不同于List和Set。

假设有一个Car类,两个属性为id和name,如下所示:

package org.shirdrn.entity;

public class Car {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

一个公司Company有多辆公用Car,而且是用Map定义的,键为Car对象,值为String类型,描述Car的用途。在Company类中添加属性:

private Map cars = new HashMap(0);

同时添加对应的Setter和Getter方法。

配置文件applicationContext.xml中,增加两个bean分别为car1Bean和car2Bean:

<bean id="car1Bean" class="org.shirdrn.entity.Car" abstract="false"
singleton="true" lazy-init="default" autowire="default"
dependency-check="default">
<property name="id">
<value>JL001</value>
</property>
<property name="name">
<value>宝马7系</value>
</property>
</bean>


<bean id="car2Bean" class="org.shirdrn.entity.Car" abstract="false"
singleton="true" lazy-init="default" autowire="default"
dependency-check="default">
<property name="id">
<value>BJ007</value>
</property>
<property name="name">
<value>劳斯莱斯</value>
</property>
</bean>

同时在id为company的bean中增加如下属性配置,使用map元素:

<property name="cars">
<map>
<entry>
<key>
<ref bean="car1Bean" />
</key>
<value>出差专用</value>
</entry>

<entry>
<key>
<ref bean="car2Bean" />
</key>
<value>旅行专用</value>
</entry>
</map>
</property>

map元素的子元素entry表示一个键值对,其中entry的子元素key表示键,value表示值。

一共有4中组合方式:

键为value类型,值为value类型;

键为ref类型,值为value类型;

键为value类型,值为ref类型;

键为ref类型,值为ref类型。

如果想要获取公司的公用车辆对象,同时获取它的用途,可以编写如下测试程序,代码如下:

package org.shirdrn.main;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.shirdrn.entity.Car;
import org.shirdrn.entity.Company;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Main {
public static void main(String[] args){
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Company c = (Company)ctx.getBean("companyBean");
Map cars = c.getCars();
Set keySet = cars.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
Car car = (Car)it.next();
String value = (String)cars.get(car);
System.out.println("the car "+car.getName()+"'s value is: "+value);
}
}
}

测试输出结果如下所示:

the car 宝马7系's value is: 出差专用
the car 劳斯莱斯's value is: 旅行专用

注意:

如果使用entry元素的属性配置,则注入Map的配置更加简洁,上面的Map注入只需要使用如下两行:

<entry key-ref="car1Bean" value="出差专用" />

<entry key-ref="car2Bean" value="旅行专用" />

让键使用ref类型,而值使用refref,配置bean如下:

<bean id="companyBean" class="org.shirdrn.entity.Company"
abstract="false" singleton="true" lazy-init="default"
autowire="default" dependency-check="default">
<property name="cars">
<map>
<entry>
<key>
<ref bean="car1Bean" />
</key>
<ref bean="car1Bean" />
</entry>
<entry>
<key>
<ref bean="car2Bean" />
</key>
<ref bean="car2Bean" />
</entry>
</map>
</property>
</bean>

测试程序代码如下:

package org.shirdrn.main;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.shirdrn.entity.Car;
import org.shirdrn.entity.Company;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class Main {
public static void main(String[] args){
ApplicationContext ctx = new FileSystemXmlApplicationContext("src/applicationContext.xml");
Company c = (Company)ctx.getBean("companyBean");
Map cars = c.getCars();
Set keySet = cars.keySet();
Iterator it = keySet.iterator();
while(it.hasNext()){
Car car = (Car)it.next();
Car value = (Car)cars.get(car);
System.out.println("the "+car+" car's value(id) is: "+value.getId());
System.out.println("the "+car+" car's value(name) is: "+value.getName());
}
}
}

测试结果输入如下:

the org.shirdrn.entity.Car@fa7e74 car's value(id) is: JL001
the org.shirdrn.entity.Car@fa7e74 car's value(name) is: 宝马7系
the org.shirdrn.entity.Car@183f74d car's value(id) is: BJ007
the org.shirdrn.entity.Car@183f74d car's value(name) is: 劳斯莱斯

只不过,此时Map的值是一个对象,根据Map的键,是一个对象,获取此键对应的值,就能够获取一个对象的相信信息。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值