Spring之構造注入與設值注入
Spring學了好久了,但是一直沒時間總結,總是斷斷續續的,這段時間打算重新做下Spring這方面的功課。
這幾天閒着沒事趕緊做做總結。Spring的核心就是控制反轉和依賴注入,依賴注入又可以分成構造注入和設值注入,使用構造注入可以在構建對象的同時一併完成依賴關係的建立,在對象的關係比較多時爲了避免使用構造注入時造成的代碼量過多,我們可以考慮使用設值注入。但是設置注入不能保證數據在執行過程中不被更改設定,所以我們要是想讓一些數據變成只讀或者私有,使用構造注入會好一點。
不過貌似設值注入用的更多一點。
首先建一個Web工程,然後將Spring的依賴包添加進去,
然後把Spring的核心配置文件beans.xml添加到src文件夾下面,創建HelloWorld.java程序如下:
package com.spring.test;
public class HelloWorld {
private String message;
public HelloWorld() {
}
public HelloWorld(String message) {
super();
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
然後在beans.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.5.xsd"> <bean id="helloWorld" class="com.spring.test.HelloWorld"> <constructor-arg index="0"> <value>I am ZDX</value> </constructor-arg> </bean> </beans>
以上這種配置方式是構造注入,設值注入需要在beans.xml中這樣設置:
<bean id="helloWorld" class="com.spring.test.HelloWorld"> <property name="message"> <value>I am ZDX</value> </property> </bean>
然後編寫測試代碼:
package com.spring.test;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldTest {
@Test
public void test() {
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld=(HelloWorld) context.getBean("helloWorld");
System.out.println(helloWorld.getMessage());
}
}
還沒深入,大概寫一下。。。。