第一章 Spring的下載和準備
很淺顯的道理,要使用Spring,必須先得到它:
從http://www.springsource.org/download,找到如圖所示:
Spring Framework 2.5.6.SEC01 is the latest Spring 2.5.x release (compatible with Java 1.4+)
點擊Download進入:填寫一堆註冊信息後,找到:
下載:spring-framework-2.5.6-with-dependencies.zip (sha1) 79.5 MB ,裏面包含源碼和例子。
解壓,我的目錄是:E:\spring-framework-2.5.6,如圖所示:
(師傅電腦的背景是淡綠色的,主要是爲了保護眼睛)調色板是:
在該目錄下可以找到:
dist\spring.jar
lib\jakarta-commons\commons-logging.jar
搭建Java-Project或者Web-Project時,以上兩個必須使用。
如果使用了切面編程(aop),還需要下列jar文件
lib/aspectj/aspectjweaver.jar
lib/aspectj/aspectjrt.jar
lib/cglib/cglig-nodep-2.1_3.jar
如果使用了JSR-250的註解,如@Resource/@PostConstruct/@PreDestrovy,還需要下列jar文件。
lib/j2ee/common-annotations.jar
採用註解還必須修改spring的xml文件,以
spring-framework-2.5.6\samples\jpetstore\war\WEB-INF\
applicationContext.xml
作爲模板進行修改,刪除所有的bean,只剩下beans
例如:
<?xml version="1.0" encoding="UTF-8"?>
<!--
- Application context definition for JPetStore's business layer.
- Contains bean references to the transaction manager and to the DAOs in
- dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
</beans>
因爲aop和tx沒有用到,我刪除了,如果你使用了,可以參考上面的。
我簡單修改瞭如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
</beans>
這個配置隱式註冊了多個對註釋進行解析處理的處理器:
AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor
推薦使用@Resource註解 是jdk提供的。
1、屬性注入
2、屬性的setter方法注入。
當然,師傅的原則是,最少包原則,當運行報錯的時候,根據錯誤在目錄下查找相應的包,添加到項目中。