摘要:
spring
两种常用的注入方式(
Type 2 Ioc
,
Type 3 Ioc
)
●
HelloBean.java
package com.kela.spring.ioc;
public class HelloBean {
private String name;
private String helloWord;
public HelloBean() {
}
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;
}
}
该程序文件中讲两种常用的注入方式写在了一起。
●
Beans-config_1.xml
<?xml
version=
"1.0"
encoding=
"GB2312"
?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd"
>
<beans>
<!--
Type
3
Injection
通过构造方法(这里注意构造方法中参数的顺序保持一致)
-->
<bean
id=
"helloBean_1"
class=
"com.kela.spring.ioc.HelloBean"
>
<constructor-arg
index=
"0"
>
<value>
KangFeng
</value>
</constructor-arg>
<constructor-arg
index=
"1"
>
<value>
你好!
</value>
</constructor-arg>
</bean>
<!--
Type2
Injection
通过
set
注入法
-->
<bean
id=
"helloBean_2"
class=
"com.kela.spring.ioc.HelloBean"
>
<property
name=
"name"
>
<value>
Kela
</value>
</property>
<property
name=
"helloWord"
>
<value>
hello
!
</value>
</property>
</bean>
</beans>
●
TestClass.java
package com.kela.spring.ioc;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class TestClass {
public void method_1() {
try {
ApplicationContext context = new
FileSystemXmlApplicationContext("bin\\com\\kela\\spring\\ioc\\beans-config_1.xml");
HelloBean helloBean_1 = (HelloBean)context.getBean("helloBean_1");
System.out.println("
构造方法注入(欢迎词):" + helloBean_1.getName() + ";" + helloBean_1.getHelloWord());
HelloBean helloBean_2 = (HelloBean)context.getBean("helloBean_2");
System.out.println("set
方法注入(欢迎词):" + helloBean_2.getName() + ";" + helloBean_2.getHelloWord());
} catch (Exception e) {
System.out.println("[ERROR]" + e.getMessage());
}
}
public static void main(String[] args) {
TestClass testClass = new TestClass();
testClass.method_1();
}
}
●
学习小结
关于Constructor和Setter注入的区别其实就是说,是要在对象建时是就准备好资源还是在对象建立好之后,再使用Setter方法来进行设定。
从实际使用角度来看,一个适用于较短的属性列,一个适用于较长的属性列。