java spring bean

在前面的程序中,以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会是个简单的选择。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值