上文讲了基于构造器进行依赖注入,这里讲解基于Setter方法进行注入。在Java世界中有个约定(Convention),那就是属性的设置和获取的方法名一般是:set+属性名(参数)及get+属性名()的方式。boolean类型稍有不同,可以使用is+属性名()方式来获取。

以下是一个示例。

MessageHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class MessageHandler {

    private MessageService messageService;

    public MessageService getMessageService() {
return messageService;
} public void setMessageService(MessageService messageService) {
this.messageService = messageService;
} public String handle() {
return messageService.sendService();
}
}

使用Setter方法注入如下所示。

1
2
3
4
<bean id="messageService" class="huangbowen.net.DependecyInjection.ConstructorInjection.SimpleMessageService"/>
<bean id="messageHandler" class="huangbowen.net.DependecyInjection.SetterInjection.MessageHandler">
<property name="messageService" ref="messageService"/>
</bean>

如果property的name为messageService,那么必须在类中有个叫做setMessageService的方法,这样才能完成注入。如果将MessageHandler.java中的setMessageService方法改为setMessageService1,那么注入就会失败,失败message如下所示。

1
2
3
4
5
6
7
...
java.lang.IllegalStateException: Failed to load ApplicationContext ...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageHandler' defined in class path resource [spring-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'messageService' of bean class [huangbowen.net.DependecyInjection.SetterInjection.MessageHandler]: Bean property 'messageService' is not writable or has an invalid setter method. Did you mean 'messageService1'? ...

当然可以同时使用构造器注入和setter方法注入。

Person.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Person {

    private String name;

    public Person(String name) {
this.name = name;
} private int age; public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public String getName() {
return name;
}
}

bean定义如下:

1
2
3
4
    <bean id="person" class="huangbowen.net.DependecyInjection.SetterInjection.Person">
<constructor-arg value="Tom"/>
<property name="age" value="20"/>
</bean>

要实现一个bean,即可以使用构造器注入,也可以使用setter注入,甚至可以在一个bean中综合使用这两种方式。那么在真正开发中应该作何取舍那?一般来说,使用构造器注入的依赖必须是强制的依赖,而使用setter注入的依赖则是可选的依赖。使用构造器注入生成的对象是完全初始化了的,用户可以直接拿来用,但是相比于setter方法而言用户也就失去了定制化的能力。如果你发现构造器参数过多,那么很可能说明该类承担的职责过多,应该从设计解耦的角度对类的职责进行拆分。使用setter注入的对象好处是,用户可以按需重新注入新的属性。

另外在进行依赖注入时,可以将某些属性抽出来成为一个元素,或者将元素内联成为一个属性。比如ref这个属性。

1
2
3
    <bean id="messageHandler" class="huangbowen.net.DependecyInjection.SetterInjection.MessageHandler">
<property name="messageService" ref="messageService" />
</bean>

它与以下xml配置完全等价。

1
2
3
4
5
 <bean id="messageHandler" class="huangbowen.net.DependecyInjection.SetterInjection.MessageHandler">
<property name="messageService">
<ref bean="messageService"/>
</property>
</bean>

value属性也可以独立为元素。

1
2
3
4
    <bean id="person" class="huangbowen.net.DependecyInjection.SetterInjection.Person">
<constructor-arg value="Tom"/>
<property name="age" value="20"/>
</bean>

其等价于:

1
2
3
4
5
6
    <bean id="person" class="huangbowen.net.DependecyInjection.SetterInjection.Person">
<constructor-arg value="Tom"/>
<property name="age">
<value>20</value>
</property>
</bean>

也可以显式指定value的类型。

1
2
3
4
5
6
    <bean id="person" class="huangbowen.net.DependecyInjection.SetterInjection.Person">
<constructor-arg value="Tom"/>
<property name="age">
<value type="int">20</value>
</property>
</bean>

比如有一个属性是个boolean值,如果想将其注入为true的话,不指定具体类型的话,Spring可能会将其作为字符串true对待。当然Spring会尝试将传入的字符串转换为setter方法希望的类型,但这种自动转换有时候并不是你期望的,这种情况下你就需要显式指定其类型。

本例中的源码请在我的GitHub上自行下载。

Spring-Context之六:基于Setter方法进行依赖注入的更多相关文章

  1. Spring基于Setter函数的依赖注入(DI)

    以下内容引用自http://wiki.jikexueyuan.com/project/spring/dependency-injection/spring-setter-based-dependenc ...

  2. Spring 基于set方法的依赖注入

    注意,再次强调,注入一个值用value,注入一个引用,要使用    ref   来注入 同时,注入的对象,要有set和get方法,才能通过方法注入. <?xml version="1. ...

  3. 三大框架 之 Spring(IOC控制反转、DI依赖注入)

    目录 常用词汇 left join与left outer join的区别 Struts2的标签库导入 Spring Spring概述 什么是Spring spring特点 下载 IOC 什么IOC 传 ...

  4. Spring详解(三)------DI依赖注入

    上一篇博客我们主要讲解了IOC控制反转,也就是说IOC 让程序员不在关注怎么去创建对象,而是关注与对象创建之后的操作,把对象的创建.初始化.销毁等工作交给spring容器来做.那么创建对象的时候,有可 ...

  5. Spring_01 spring容器、控制反转(IOC)、依赖注入(DI)

    目录 1 什么是spring框架 2 spring框架的特点 3 spring容器 3.1 什么是spring容器 3.2 spring容器创建对象的编程步骤 3.4 spring容器创建对象的方式 ...

  6. Spring IOC源代码具体解释之容器依赖注入

    Spring IOC源代码具体解释之容器依赖注入 上一篇博客中介绍了IOC容器的初始化.通过源代码分析大致了解了IOC容器初始化的一些知识.先简单回想下上篇的内容 加载bean定义文件的过程.这个过程 ...

  7. Spring升级案例之IOC介绍和依赖注入

    Spring升级案例之IOC介绍和依赖注入 一.IOC的概念和作用 1.什么是IOC 控制反转(Inversion of Control, IoC)是一种设计思想,在Java中就是将设计好的对象交给容 ...

  8. spring 配置bean的方法及依赖注入发方式

    Bean 的配置方式:通过全类名(反射).通过工厂方法(静态工厂方法 & 实例工厂方法).FactoryBean 这里依据全类名配置bean <bean id="helloWo ...

  9. 基于反射的通过set方法的依赖注入,可以看成一种设计模式,自己来用

    非常好用,在properties文件中配置字符串和类名之间的对应,在程序里读取文件,找到类名,通过反射,达到调用set方法的目的,然后直接将自己的指向其他类的对象的引用赋值,指向实体对象. 比如use ...

随机推荐

  1. [03]APUE:文件 I/O

    [a] open #include <fcntl.h> int open(const char *path, int oflag, ... ,mode_t mode) 成功返回文件描术符, ...

  2. .net 发展史

    2002年年初 -Visual Studio 2002 & .Net Framework 1.0 2003年春天 -Visual Studio 2003 & .Net Framewor ...

  3. Cracking-- 17.13 将二叉树转换成双向链表

    在书的105页 使用中根遍历的思想 left 之后 为 root 之后 为 right 则对左子树来说 left->right = root; root->left = left; 对右子 ...

  4. HttpWebRequest header configuration

    more details: http://www.cnblogs.com/yczz/archive/2012/06/01/2530484.html 在HttpWebRequest中,有一些header ...

  5. SQL一致性错误修复SQL

    USE master; ); SET @databasename = 'BenlaiTask'; ALTER DATABASE BenlaiTask SET SINGLE_USER WITH ROLL ...

  6. 解决 IE 6/7 中console对象兼容性问题

    话不多说,直接上代码 (function (){ //创建空console对象,避免JS报错 if(!window.console) window.console = {}; var console ...

  7. 核心动画(CAKeyframeAnimation)

    Main.storyboard ViewController.m // //  ViewController.m //  8A02.核心动画 - CAKeyframeAnimation // //  ...

  8. Python生成器的经典程序

    import random def get_data(): """返回0到9之间的3个随机数""" return random.sample ...

  9. Discuz!X2大附件上传插件-Xproer.HttpUploader6

    插件代码(github):https://github.com/1269085759/up6-discuz 插件代码(coding):https://coding.net/u/xproer/p/up6 ...

  10. 【转】Linux中xargs的用法

    xargs大 多数 Linux 命令都会产生输出:文件列表.字符串列表等.但如果要使用其他某个命令并将前一个命令的输出作为参数该怎么办?例如,file 命令显示文件类型(可执行文件.ascii 文本等 ...