摘要:
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方法來進行設定。
從實際使用角度來看,一個適用于較短的屬性列,一個適用于較長的屬性列。