首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring核心技术-IoC的Bean根本管理2

2012-11-04 
Spring核心技术----IoC的Bean基本管理2在前面的程序中,以Bean的Setter方法完成依赖注入.?? Spring鼓励的是

Spring核心技术----IoC的Bean基本管理2

在前面的程序中,以Bean的Setter方法完成依赖注入.?? Spring鼓励的是Setter Injection(set方法注入) 当也可以使用Constructor injection(构造方法注入),要使用Setter或?Constructor来注入依赖关系视需求而定。

?

?Constructor injection(构造方法注入)的示例:

============

HelloBean.java

-------------------------------------------------------

package only;

public class HelloBean {
? ?public String name;
???public String helloWord;
?
?? public HelloBean(String name,String helloword){
??????????? this.name=name;
??????????? this.helloWord=helloword;
?? }

?? public String getHelloWord() {
???????????? return helloWord;
?? }

?? public void setHelloWord(String helloWord) {
??????????????this.helloWord = helloWord;
?? }

? ?public String getName() {
??????????????return name;
?? }

???public void setName(String name) {
????????????? this.name = name;
??}
}

===================

applicationContext.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"
?xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

?

<!--在这里使用<constructor-arg >标签来表示将使用Contructpr Injection(构造函数注入)-->

<!--index属性就是指定对象将注入至构造函数中的哪一个位置的参数,参数的顺序指定中第一个参数用“0”表示,第二个用“1”,依此类推-->
?<bean id="helloBean" class="only.HelloBean">
?? <constructor-arg index="0">
??????? ?<value>Justin</value>
?? </constructor-arg>


?? <constructor-arg index="1">
?????????<value>Hello</value>
?? </constructor-arg>
?</bean>
</beans>

==============

SpringDemo .java

-------------------------------------------------

package only;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class SpringDemo {

?/**
? * @param args
? */
?public static void main(String[] args) {
???????? ?ApplicationContext context=
????????????? ?new FileSystemXmlApplicationContext("src/applicationContext.xml");
???????? ??HelloBean hello=(HelloBean)context.getBean("helloBean");
????????? System.out.print("name:");
??????????System.out.println(hello.getName());
????????? System.out.print("Word:");
????????? System.out.println(hello.getHelloWord());
? ?}
}

?

??? 至于要使用Constructor或Setter方法来完成依赖注入这个问题,其实就等于在讨论一个古老的问题:要在对象建立时就准备好所有的资源,或是在对象建立好后,在使用setter方法来进行设定。

??? 使用Constructor的好处之一是,可以在构造对象的同时一并完成依赖关系的建立,对象一建立后,它与其他对象的依赖关系也就准备好了,但如果建立的对象关系很多,使用Constructor injection会在构造方法上留下一长串的参数,且不易记忆,这时使用setter方法会是一个不错的选择,另一方面,setter方法具有明确的方法名称可以了解注入的对象是什么,像setxxx()这样的名称,会比Contructor上某个参数位置的索引代表某个对象来得好,当结合IDE的方法提示功能使用时,编程会更方便且有效率。

??? 然而使用setter方法时,由于提供有setxxx()方法,因此不能保证相关的数据成员或资源在执行时期不会被更改设定,因为程序开发人员可能执行setxxx()方法来设定相关属性,所以如果想要让一些数据成员或资源变为只读或是私有,使用Constructor injection会是个简单的选择。