Spring就是這樣一個框架:你可以選擇不使用這個框架,但你的開發架構一定會暗合它的思想。
Spring簡介
在Web應用中使用Spring
commons-logging-1.2.jar包也是需要的
Spring 的核心機制:依賴注入
- 設置注入:IOC容器使用屬性setter方法來注入被依賴的實例
- 構造注入:IOC容器使用構造器來注入被依賴的實例
一、設置注入
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="personService" class="awen.PersonService"> <property name="name" value="AWen" /> </bean> </beans>
二、構造注入
構造實例時,已經為其完成了依賴關系的初始化,這種利用構造器來設置依賴關系的方法,稱為構造注入
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="personService" class="awen.PersonService"> <constructor-arg index="0" value="wxc" /> </bean> </beans>
建議采用以設置注入為主,構造注入為輔的注入策略。對於依賴關系無須變化的注入,盡量采用構造注入,而其他的依賴關系的注入,則考慮采用設置注入