Spring——基本概念(IOC,DI思想),Spring配置文件(XML),屬性注入,Spring與Web項目結合

Spring簡介

spring是一站式框架;正是由於spring框架性質是屬於容器性質的,容器中裝什麼對象就有什麼功能,因此能夠一站式,不只不排斥其餘框架,還能幫其餘框架管理對象。html

  • aop支持
  • ioc思想
  • spring jdbc
  • aop 事務
  • junit 測試支持

Spring的搭建

一、導包

com.springsource.org.apache.log4j-1.2.15.jar(可選)java

二、建立一個對象

三、書寫配置註冊對象到容器

位置任意(建議放到src下)web

配置文件名任意(建議applicationContext.xml)spring

導入約束apache

四、代碼測試

Spring的基本概念

一、IOC思想(由本身建立改爲了由程序建立)

二、DI思想

三、applicationContext&BeanFactory

BeanFactory接口數組

  • spring原始接口.針對原始接口的實現類功能較爲單一
  • BeanFactory接口實現類的容器.特色是每次在得到對象時纔會建立對象

ApplicationContextsession

  • 每次容器啓動時就會建立容器中配置的全部對象.並提供更多功能
  • 叢類路徑下加載配置文件:ClassPathXmlApplicationContext
  • 從硬盤絕對路徑下加載配置文件:FileSystemXmlApplicationContext("d:/xxx/yyy/xxx")

結論:web開發中,使用applicationContext. 在資源匱乏的環境能夠使用BeanFactoryapp

Spring配置

一、Bean元素下的基本屬性

<!-- 將User對象交給spring容器管理 -->
<!-- Bean元素:使用該元素描述須要spring容器管理的對象
		class屬性:被管理對象的完整類名.
		name屬性:給被管理的對象起個名字.得到對象時根據該名稱得到對象.  
				能夠重複.能夠使用特殊字符.
		id屬性: 與name屬性如出一轍. 
				名稱不可重複.不能使用特殊字符.
		結論: 儘可能使用name屬性.
		scope屬性:
			singleton(默認值):單例對象.被標識爲單例的對象在spring容器中只會存在一個實例
			prototype:多例原型.被標識爲多例的對象,每次再得到纔會建立.每次建立都是新的對象.整合struts2時,ActionBean必須配置爲多例的.
			request:web環境下.對象與request生命週期一致.
			session:web環境下,對象與session生命週期一致.
  -->
<bean  name="user" class="cn.itcast.bean.User" scope="singleton" ></bean>
<!-- 導入其餘spring配置文件 -->
<import resource="cn/itcast/b_create/applicationContext.xml"/>
	
</beans>

二、建立對象的三種方式

a.空參構造方式
框架

b.靜態工廠(瞭解)測試

 

c.實例工廠(瞭解)

三、屬性注入

複雜類型注入

1)數組

2)集合

3)字典

4)properties(鍵值全是String類型的字典)

Spring與Web項目結合

一、導包

 spring-web-4.2.4.RELEASE.jar  // 多加一個這個包

二、 封裝Dao和Service對象(注意:service中提供set方法)

三、獲取容器

注:這是錯誤的示範.致使每次請求都建立新的容器

3.一、配置容器隨項目啓動

<!-- 可讓spring容器隨項目的啓動而建立,隨項目的關閉而銷燬 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定加載spring配置文件的位置 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-config.xml</param-value>
</context-param>

四、獲取容器

//得到spring容器=>從Application域得到便可,Spring爲咱們封裝了一個方法能夠直接獲取,但須要servletContext對象(得到application域)

//1 得到servletContext對象
ServletContext servletcontext = ServletActionContext.getServletContext();
//2.從context中得到ac容器
WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(servletcontext);
//3.從容器中得到CustomerService
CustomerService service = (CustomerService) ac.getBean("customerService");
相關文章
相關標籤/搜索