日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring学习笔记1

發(fā)布時(shí)間:2023/12/20 javascript 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring学习笔记1 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

前言

Spring框架的學(xué)習(xí)路線:

  • Spring第一天:Spring的IOC容器之XML的方式,Spring框架與Web項(xiàng)目整合
  • Spring第二天:Spring的IOC容器之注解的方式,Spring的AOP技術(shù)
  • Spring第三天:Spring的事務(wù)管理、Spring框架的JDBC模板
  • Spring第四天:SSH三大框架的整合
  • 這是第一天學(xué)習(xí)大綱:

    一、 Spring框架的概述

    1.1 技術(shù)分析之什么是Spring框架

    1、Spring框架的概述:(更詳細(xì)參考百度百科 spring)

    • Spring是一個(gè)開源框架
    • Spring是于2003 年興起的一個(gè)輕量級的Java開發(fā)框架,由Rod Johnson在其著作Expert One-On-One J2EE Development and Design中闡述的部分理念和原型衍生而來。
    • 它是為了解決企業(yè)應(yīng)用開發(fā)的復(fù)雜性而創(chuàng)建的。框架的主要優(yōu)勢之一就是其分層架構(gòu),分層架構(gòu)允許使用者選擇使用哪一個(gè)組件,同時(shí)為 J2EE 應(yīng)用程序開發(fā)提供集成的框架。
      Spring使用基本的JavaBean來完成以前只可能由EJB完成的事情。然而,Spring的用途不僅限于服務(wù)器端的開發(fā)。從簡單性、可測試性和松耦合的角度而言,任何Java應(yīng)用都可以 從Spring中受益。
    • Spring的核心是控制反轉(zhuǎn)(IoC)和面向切面(AOP)。簡單來說,Spring是一個(gè)分層的JavaSE/EEfull-stack(一站式) 輕量級開源框架。

    引用百度百科上一段介紹:

    Rod Johnson在2002年編著的《Expert one on one J2EE design and development》一書中,對Java EE 系統(tǒng)框架臃腫、低效、脫離現(xiàn)實(shí)的種種現(xiàn)狀提出了質(zhì)疑,并積極尋求探索革新之道。以此書為指導(dǎo)思想,他編寫了interface21框架,這是一個(gè)力圖沖破J2EE傳統(tǒng)開發(fā)的困境,從實(shí)際需求出發(fā),著眼于輕便、靈巧,易于開發(fā)、測試和部署的輕量級開發(fā)框架。Spring框架即以interface21框架為基礎(chǔ),經(jīng)過重新設(shè)計(jì),并不斷豐富其內(nèi)涵,于2004年3月24日,發(fā)布了1.0正式版。同年他又推出了一部堪稱經(jīng)典的力作《Expert one-on-one J2EE Development without EJB》,該書在Java世界掀起了軒然大波,不斷改變著Java開發(fā)者程序設(shè)計(jì)和開發(fā)的思考方式。在該書中,作者根據(jù)自己多年豐富的實(shí)踐經(jīng)驗(yàn),對EJB的各種笨重臃腫的結(jié)構(gòu)進(jìn)行了逐一的分析和否定,并分別以簡潔實(shí)用的方式替換之。至此一戰(zhàn)功成,Rod Johnson成為一個(gè)改變Java世界的大師級人物。

    解釋:最早做 Java 開發(fā)采用的是 sun 公司提供的 EJB 規(guī)范做開發(fā),最開始沒那么多框架。Rod Johnson 對開發(fā)過程諸如低效、臃腫、脫離現(xiàn)實(shí)種種現(xiàn)狀提出質(zhì)疑,并積極尋求探索革新之道,后來就有了 spring 框架。

    2、EE開發(fā)分成三層結(jié)構(gòu)

    • WEB層 – Spring MVC
      業(yè)務(wù)層 – Bean管理:(IOC)
      持久層 – Spring的 JDBC 模板. ORM模板用于整合其他的持久層框架

    3、什么叫full-stack(一站式)開發(fā)?

    首先來說 Java EE 開發(fā)一般分三層,WEB 層、業(yè)務(wù)層、持久層,每一層要干的事不一樣。如下:

    Spring 屬于業(yè)務(wù)層一個(gè)框架,那為什么叫一站式開發(fā)呢?這樣來解釋,如果 WEB 層你不想使用 Struts2 框架,Spring 框架提供了一個(gè)叫 SpringMVC 模塊(屬于 Spring 的一部分),它就可以當(dāng)做 WEB 層小框架,處理 web 層事情;如果持久層不想使用 Hibernate 框架,Spring 框架提供了一個(gè)叫 SpringJDBC 模板(它能幫忙操作數(shù)據(jù)庫),這樣它就能當(dāng)做持久層解決方案。

    這樣看來,如果我不使用其他框架,只用 Spring 框架也是能做 Java EE 開發(fā)。并且如果你不想使用 SpringMVC 模塊做 WEB 層也是可以的,仍然可以使用 Struts2 框架,因?yàn)?Spring 框架可以幫忙集成和整合 Struts2 框架;如果持久層你不想使用 SpringJDBC 模板,使用其他一些持久層框架如 Hibernate、Mybatis 也是可以,Spring 框架也可以去整合它們。

    另外,如果沒有 Spring 框架,只用 Struts2 開發(fā)也是沒問題,但可能效率等方面就不是很好了。但有了 Spring 框架,Struts2 會(huì)更牛,它的管理可能更方便、開發(fā)更簡單。簡單來說:只用 Struts2 去開發(fā)也可以,但是有了 Spring 框架開發(fā)會(huì)更好。

    再次小結(jié):如果沒有 Spring 框架也能做企業(yè)級開發(fā),但有了 Spring,做開發(fā)更規(guī)范,程序擴(kuò)展性和維護(hù)等方面更好。-----> 它能解決企業(yè)級開發(fā)的復(fù)雜性。

    另外關(guān)于 Spring 框架,我們再來了解下它與 Spring boot、Spring Clound 的區(qū)別:Spring SpringMVC SpringBoot SpringCloud概念、關(guān)系及區(qū)別

    1.2 技術(shù)分析之Spring框架的特點(diǎn)

    1、 為什么要學(xué)習(xí)Spring的框架

    • 方便解耦,簡化開發(fā)
      • Spring就是一個(gè)大工廠,可以將所有對象創(chuàng)建和依賴關(guān)系維護(hù),交給Spring管理
    • AOP編程的支持
      • Spring提供面向切面編程,可以方便的實(shí)現(xiàn)對程序進(jìn)行權(quán)限攔截、運(yùn)行監(jiān)控等功能
    • 聲明式事務(wù)的支持
      • 只需要通過配置就可以完成對事務(wù)的管理,而無需手動(dòng)編程
    • 方便程序的測試
      • Spring對Junit4支持,可以通過注解方便的測試Spring程序
    • 方便集成各種優(yōu)秀框架
      • Spring不排斥各種優(yōu)秀的開源框架,其內(nèi)部提供了對各種優(yōu)秀框架(如:Struts2、Hibernate、MyBatis、Quartz等)的直接支持
    • 降低JavaEE API的使用難度
      • Spring 對JavaEE開發(fā)中非常難用的一些API(JDBC、JavaMail、遠(yuǎn)程調(diào)用等),都提供了封裝,使這些API應(yīng)用難度大大降低

    2、Spring框架的版本:

    • Sring3.x 和 Spring4.x 的版本

    二、SpringIOC的快速入門

    1、什么是 IOC 的功能?

    • IoC(Inverse of Control):控制反轉(zhuǎn),將對象的創(chuàng)建權(quán)反轉(zhuǎn)給Spring!!
    • 使用 IOC 可以解決的程序耦合性高的問題!!

    如上圖,解釋一下。

    假如要做一個(gè)保存客戶信息的功能,那么我們在代碼中可能要在 service 層 new 一個(gè)類,再到 dao 層 new 一個(gè)類(類比上圖即資源),可以看到,資源的創(chuàng)建權(quán)利來自該功能。其實(shí)這樣不是不可以,只是不好,過度耦合了。有了 Spring 框架,那現(xiàn)在可以交給 Spring 框架了。

    IOC 的編寫過程:(先要了解工廠模式,參考 工廠模式——看這一篇就夠了)

    • App —> 工廠 —> 資源(功能和資源分開了,但是有個(gè)問題,資源和工廠還存在耦合)

    • App —> 工廠 —> XML文件 —> 資源

      在 xml 文件中配置,配置什么,就創(chuàng)建什么。工廠讀取 xml 文件,工廠負(fù)責(zé)生產(chǎn)這些對象。程序中用到對象就到工廠拿就可以。

    IOC 的底層實(shí)現(xiàn)原理:

    編寫步驟:

    1. 步驟一:下載Spring框架的開發(fā)包* 官網(wǎng):http://spring.io/* 下載地址:http://repo.springsource.org/libs-release-local/org/springframework/spring 解壓出來:(Spring目錄結(jié)構(gòu):)* docs -- API和開發(fā)規(guī)范* libs -- jar包和源碼* schema -- 約束2. 步驟二:創(chuàng)建JavaWEB項(xiàng)目,引入Spring的開發(fā)包* 引入Spring框架IOC核心功能需要的具體的jar包* Spring框架的IOC的功能,那么根據(jù)Spring框架的體系結(jié)構(gòu)圖能看到,只需要引入如下的jar包* Beans* Core* Context* Expression Language* Spring框架也需要引入日志相關(guān)的jar包* 在spring-framework-3.0.2.RELEASE-dependencies/org.apache.commons/com.springsource.org.apache.commons.logging/1.1.1* com.springsource.org.apache.commons.logging-1.1.1.jar* 還需要引入log4j的jar包 spring-framework-3.0.2.RELEASE-dependencies\org.apache.log4j\com.springsource.org.apache.log4j\1.2.15* com.springsource.org.apache.log4j-1.2.15.jar3. 步驟三:創(chuàng)建對應(yīng)的包結(jié)構(gòu),編寫Java的類,要注意:以后使用Spring框架做開發(fā),都需要來編寫接口與實(shí)現(xiàn)類!!* com.itcast.demo1* UserService -- 接口* UserServiceImpl -- 具體的實(shí)現(xiàn)類4. 步驟四:想把UserServiceImpl實(shí)現(xiàn)類的創(chuàng)建交給Spring框架來管理,需要?jiǎng)?chuàng)建Spring框架的配置文件,完成配置* 在src目錄下創(chuàng)建applicationContext.xml的配置文件,名稱是可以任意的,但是一般都會(huì)使用默認(rèn)名稱!!* 引入spring的約束,需要先找到具體的約束頭信息!!* spring-framework-3.2.0.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html* 具體的約束如下: <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.xsd"></beans>* 完成UserService的配置<!-- Spring的快速入門 --><bean id="userService" class="com.itcast.demo1.UserServiceImpl"/>5. 步驟五:編寫測試程序,采用Spring框架的工廠方式來獲取到UserService接口的具體實(shí)現(xiàn)類!!public void demo2(){// 使用Spring的工廠:ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");// 通過工廠獲得類:UserService userService = (UserService) applicationContext.getBean("userService");userService.sayHello();}

    關(guān)于第①步: 相關(guān) Spring 文件有如下:

    但我們用到的核心的是 spring-framework-4.2.4.RELEASE-dist.zip 該文件,把其解壓出來可以看到存在 docs文件夾(文檔) 和 scheme文件夾(約束);另外一個(gè)文件 spring-framework-3.0.2.RELEASE-dependencies.zip是有關(guān)依賴包的文件,如文件上傳、連接池、日志相關(guān)包。

    關(guān)于第②步:

    看上圖上半部分 Spring Framework Runtime,可以看到核心容器下有四個(gè)模塊,上面其他功能都依賴該四個(gè)模塊。所以只要導(dǎo)入四個(gè)包就可以。(在這里,另外導(dǎo)入了spring-framework-3.0.2.RELEASE-dependencies.zip中兩個(gè)依賴包,第一個(gè)為日志規(guī)范,第二個(gè)為日志實(shí)現(xiàn))

    關(guān)于日志,其實(shí)還少了一個(gè)配置文件 log4j.properties,內(nèi)容:

    ### direct log messages to stdout ### log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.err log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file mylog.log ### log4j.appender.file=org.apache.log4j.FileAppender log4j.appender.file.File=c\:mylog.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###log4j.rootLogger=info, stdout

    把日志配置文件粘貼到項(xiàng)目 src 目錄下。

    注:log4j.rootLogger=info, stdout 中 info 表示級別,stdout 表示向控制臺(tái)輸出。如 info 可改為 off 則不會(huì)在輸出日志信息,還可設(shè)置為 debug。

    代碼演示:

    public class Demo1 {//創(chuàng)建日志對象private Logger log = Logger.getLogger(Demo1.class);@Testpublic void run1() {// System.out.println("執(zhí)行了...");log.info("執(zhí)行了...");} }

    結(jié)果:

    關(guān)于第③步:

    UserService.java:

    public interface UserService {public void sayHello(); }

    UserServiceImpl.java:

    public class UserServiceImpl implements UserService {public void sayHello() {System.out.println("Hello Spring!");} }

    使用原來的方式:

    //原來的方式 @Test public void run1() {//創(chuàng)建實(shí)現(xiàn)類//UserServiceImpl us = new UserServiceImpl(); UserService us = new UserServiceImpl();us.sayHello(); }

    可以看到打印輸出:Hello Spring!

    關(guān)于第④⑤步: 在 src 目錄下創(chuàng)建applicationContext.xml的配置文件,寫上相關(guān)配置信息

    <?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:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 使用bean標(biāo)簽 --><bean id="userService" class="com.strivebo.demo2.UserServiceImpl"><property name="name" value="小鳳"/></bean> </beans>

    使用 Spring 框架的方式:

    //使用 Spring 框架的方式 @Test public void run2() {// 創(chuàng)建工廠,加載核心配置文件ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");// 從工廠中獲取到對象UserServiceImpl usi = (UserServiceImpl) ac.getBean("userService");//一般使用如下接口的方式//UserService usi = (UserService) ac.getBean("userService");// 調(diào)用對象的方法執(zhí)行usi.sayHello(); }

    同樣也是能輸出:Hello Spring!

    1.3 入門總結(jié)之Spring框架中的工廠(了解)

    1. ApplicationContext接口* 使用ApplicationContext工廠的接口,使用該接口可以獲取到具體的Bean對象* 該接口下有兩個(gè)具體的實(shí)現(xiàn)類* ClassPathXmlApplicationContext -- 加載類路徑下的Spring配置文件* FileSystemXmlApplicationContext -- 加載本地磁盤下的Spring配置文件2. BeanFactory工廠(是Spring框架早期的創(chuàng)建Bean對象的工廠接口)* 使用BeanFactory接口也可以獲取到Bean對象public void run(){BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));UserService us = (UserService) factory.getBean("us");us.sayHello();}* BeanFactory和ApplicationContext的區(qū)別* BeanFactory -- BeanFactory采取延遲加載,第一次getBean時(shí)才會(huì)初始化Bean* ApplicationContext -- 在加載applicationContext.xml時(shí)候就會(huì)創(chuàng)建具體的Bean對象的實(shí)例,還提供了一些其他的功能* 事件傳遞* Bean自動(dòng)裝配* 各種不同應(yīng)用層的Context實(shí)現(xiàn)

    三、IoC容器XML的方式

    3.1 入門總結(jié)之配置Spring框架編寫XML的提示:

    1. 步驟一:先復(fù)制, http://www.springframework.org/schema/beans/spring-beans.xsd 2. 步驟二:打開 Eclipse的Windows-->Preference,搜索XML Catalog,點(diǎn)擊Add按鈕 3. 步驟三:先選擇Location的schema的約束地址* E:\class\2016\JavaEE28\day35_Spring框架第一天\資料\spring-framework-4.2.4.RELEASE-schema\beans\spring-beans-4.2.xsd 4. 步驟四:注意:Key type要選擇:Schema location 5. 步驟五:Key把http://www.springframework.org/schema/beans/spring-beans.xsd復(fù)制上

    3.2 技術(shù)分析之Spring框架的Bean管理的配置文件方式

    3.3.1 Spring框架中標(biāo)簽的配置

    1. id屬性和name屬性的區(qū)別* id -- Bean起個(gè)名字,在約束中采用ID的約束,唯一* 取值要求:必須以字母開始,可以使用字母、數(shù)字、連字符、下劃線、句話、冒號 id:不能出現(xiàn)特殊字符* name -- Bean起個(gè)名字,沒有采用ID的約束(了解)* 取值要求:name:出現(xiàn)特殊字符.如果<bean>沒有id的話 , name可以當(dāng)做id使用* Spring框架在整合Struts1的框架的時(shí)候,Struts1的框架的訪問路徑是以/開頭的,例如:/bookAction2. class屬性 -- Bean對象的全路徑 3. scope屬性 -- scope屬性代表Bean的作用范圍* singleton -- 單例(默認(rèn)值)* prototype -- 多例,在Spring框架整合Struts2框架的時(shí)候,Action類也需要交給Spring做管理,配置把Action類配置成多例!!* request -- 應(yīng)用在Web項(xiàng)目中,每次HTTP請求都會(huì)創(chuàng)建一個(gè)新的Bean* session -- 應(yīng)用在Web項(xiàng)目中,同一個(gè)HTTP Session 共享一個(gè)Bean* globalsession -- 應(yīng)用在Web項(xiàng)目中,多服務(wù)器間的session4. Bean對象的創(chuàng)建和銷毀的兩個(gè)屬性配置(了解)* 說明:Spring初始化bean或銷毀bean時(shí),有時(shí)需要作一些處理工作,因此spring可以在創(chuàng)建和拆卸bean的時(shí)候調(diào)用bean的兩個(gè)生命周期方法* init-method -- 當(dāng)bean被載入到容器的時(shí)候調(diào)用init-method屬性指定的方法* destroy-method -- 當(dāng)bean從容器中刪除的時(shí)候調(diào)用destroy-method屬性指定的方法* 想查看destroy-method的效果,有如下條件* scope= singleton有效* web容器中會(huì)自動(dòng)調(diào)用,但是main函數(shù)或測試用例需要手動(dòng)調(diào)用(需要使用ClassPathXmlApplicationContext的close()方法)

    關(guān)于 scope 屬性 為 singleton(單例)和 prototype(多例)的理解:

    像以前的寫程序方式,每次要在 service 得 new XxxDao(),可以看出,每次發(fā)送請求,都得 new 一個(gè)對象,這就是多例。(每個(gè)請求都有一個(gè)實(shí)例對象)

    那什么是單例呢?單例相當(dāng)于整個(gè)運(yùn)行環(huán)境中就這一個(gè)實(shí)例對象。就比如 new XxxDao() 這個(gè) dao 對象已經(jīng)創(chuàng)建好了,在內(nèi)存當(dāng)中就這一個(gè)實(shí)例對象。

    關(guān)于 Spring的 bean 的單例和多例作用域更多介紹參考網(wǎng)上資料:【Spring學(xué)習(xí)17】bean作用域:單例和多例

    在 Spring 里,通過容器創(chuàng)建的對象默認(rèn)是singleton單例(這里要注意的是 singleton 作用域和 GOF 設(shè)計(jì)模式中的單例是不同的) ,單例就是在整個(gè)容器的生命周期,只會(huì)存在一個(gè)共享的bean實(shí)例。

    如果某個(gè) bean 被標(biāo)記為多例,則每次請求使用該對象時(shí),都會(huì)創(chuàng)建一個(gè)新的 bean 實(shí)例。比如將這個(gè) bean 注入到另一個(gè) bean 中,或者在程序中調(diào)用getBean("beanid")方法,都會(huì)觸發(fā)生成一個(gè)新的 bean 實(shí)例,相當(dāng)于 new 的操作。

    關(guān)于 init-method 和 destory-method 屬性,見代碼演示:

    <!-- 使用bean標(biāo)簽 --> <bean id="userService" class="com.strivebo.demo2.UserServiceImpl" init-method="init" destroy-method="destory"><property name="name" value="小鳳"/> </bean>

    UserServiceImpl.java:

    public class UserServiceImpl implements UserService {public void sayHello() {System.out.println("Hello Spring!");} public void init() {System.out.println("初始化...");}public void destory() {System.out.println("銷毀...");} }

    3.3.2 依賴注入(DI)

    什么是依賴注入?

    如上圖,我們想做一個(gè)功能,以前都是 service 層 new Dao().xxx ,可以看到 service 層需要依賴 dao,這就叫依賴。現(xiàn)在有了 Spring ,service 和 dao 都可以交給 Spring 管理。在創(chuàng)建 service 的時(shí)候,發(fā)現(xiàn)需要 dao,則會(huì)注入一個(gè) dao,那 service 就這樣有了 dao,于是便可以調(diào)用 dao 對象的方法。代碼來理解:

    UserServiceImpl.java:

    public class UserServiceImpl implements UserService {private String name;public void setName(String name) {this.name = name;}public void sayHello() {System.out.println("Hello Spring!" + name);} }

    以前方法都是:

    public void run1() {//創(chuàng)建實(shí)現(xiàn)類UserServiceImpl us = new UserServiceImpl();us.setName("小明");us.sayHello(); }

    可以看到輸出:Hello Spring!小明

    現(xiàn)在方式——依賴注入方式:

    applicationContext.xml:

    <bean id="userService" class="com.strivebo.demo2.UserServiceImpl"><property name="name" value="小鳳"/> </bean>

    執(zhí)行:

    @Test public void run2() {// 創(chuàng)建工廠,加載核心配置文件ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");UserService usi = (UserService) ac.getBean("userService");// 調(diào)用對象的方法執(zhí)行usi.sayHello(); }

    輸出結(jié)果:Hello Spring!小鳳

    -------------------------------------------代碼完整演示過程---------------------------------------------

    ①以前的方式:

    CustomerDaoImpl.java:

    public class CustomerDaoImpl {public void save(){System.out.println("我是持久層dao....");} }

    CustomerServiceImpl.java:

    public class CustomerServiceImpl {public void save(){System.out.println("我是業(yè)務(wù)層service....");new CustomerDaoImpl().save();} }

    執(zhí)行:

    @Test public void run1(){ //原始方式CustomerServiceImpl cs = new CustomerServiceImpl();cs.save(); }

    結(jié)果:

    ②依賴注入方式:

    CustomerServiceImpl.java:

    public class CustomerServiceImpl {// 提供成員屬性,提供set方法private CustomerDaoImpl customerDao;public void setCustomerDao(CustomerDaoImpl customerDao) {this.customerDao = customerDao;} public void save(){System.out.println("我是業(yè)務(wù)層service....");// 原來編寫方式// new CustomerDaoImpl().save();// Spring的方式customerDao.save();} }

    applicationContext.xml 文件添加如下:(即把 customeDao 注入到 customerService 中)

    <!-- 演示的依賴注入 --> <bean id="customerDao" class="com.strivebo.demo3.CustomerDaoImpl"/> <bean id="customerService" class="com.strivebo.demo3.CustomerServiceImpl"><property name="customerDao" ref="customerDao"/> </bean>

    運(yùn)行:

    @Test public void run2(){ //Spring 方式// 創(chuàng)建工廠,加載配置文件,CustomerDaoImpl創(chuàng)建了,CustomerServiceImpl被創(chuàng)建了,ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");CustomerServiceImpl cs = (CustomerServiceImpl) ac.getBean("customerService");cs.save(); }

    3.3.3 Spring框架的屬性注入

    1. 對于類成員變量,常用的注入方式有兩種* 構(gòu)造函數(shù)注入* 屬性setter方法注入2. 在Spring框架中提供了前兩種的屬性注入的方式1. 構(gòu)造方法的注入方式,兩步* 編寫Java的類,提供構(gòu)造方法public class Car {private String name;private double money;public Car(String name, double money) {this.name = name;this.money = money;}@Overridepublic String toString() {return "Car [name=" + name + ", money=" + money + "]";}}* 編寫配置文件<bean id="car" class="com.itheima.demo4.Car"><constructor-arg name="name" value="大奔"/><constructor-arg name="money" value="100"/></bean>* 或者<bean id="car" class="com.itheima.demo4.Car"><constructor-arg index="0" value="長安奔奔"/><constructor-arg index="1" value="45000"/></bean>2. 屬性的setter方法的注入方式* 編寫Java的類,提供屬性和對應(yīng)的set方法即可* 編寫配置文件3. 如果Java類的屬性是另一個(gè)Java的類,那么需要怎么來注入值呢?* <property name="name" rel="具體的Bean的ID或者name的值"/>* 例如:<bean id="person" class="com.itheima.demo4.Person"><property name="pname" value="美美"/><property name="car2" ref="car2"/></bean>

    3.3.4 Spring的2.5版本中提供了一種:p名稱空間的注入(了解)

    1. 步驟一:需要先引入 p 名稱空間* 在schema的名稱空間中加入該行:xmlns:p="http://www.springframework.org/schema/p"2. 步驟二:使用p名稱空間的語法* p:屬性名 = ""* p:屬性名-ref = ""3. 步驟三:測試* <bean id="person" class="com.itheima.demo4.Person" p:pname="老王" p:car2-ref="car2"/>

    3.3.5 Spring的3.0提供了一種:SpEL注入方式(了解)

    1. SpEL:Spring Expression Language是Spring的表達(dá)式語言,有一些自己的語法 2. 語法* #{SpEL}3. 例如如下的代碼<!-- SpEL的方式 --><bean id="person" class="com.itheima.demo4.Person"><property name="pname" value="#{'小風(fēng)'}"/><property name="car2" value="#{car2}"/></bean>4. 還支持調(diào)用類中的屬性或者方法* 定義類和方法,例如public class CarInfo {public String getCarname(){return "奇瑞QQ";}}

    3.3.6 數(shù)組,集合(List,Set,Map),Properties等的注入

    1. 如果是數(shù)組或者List集合,注入配置文件的方式是一樣的<bean id="collectionBean" class="com.itheima.demo5.CollectionBean"><property name="arrs"><list><value>美美</value><value>小風(fēng)</value></list></property></bean>2. 如果是Set集合,注入的配置文件方式如下:<property name="sets"><set><value>哈哈</value><value>呵呵</value></set></property>3. 如果是Map集合,注入的配置方式如下:<property name="map"><map><entry key="老王2" value="38"/><entry key="鳳姐" value="38"/><entry key="如花" value="29"/></map></property>4. 如果是properties屬性文件的方式,注入的配置如下:<property name="pro"><props><prop key="uname">root</prop><prop key="pass">123</prop></props></property>

    3.3.7 Spring框架的配置文件分開管理(了解)

    1. 例如:在src的目錄下又多創(chuàng)建了一個(gè)配置文件,現(xiàn)在是兩個(gè)核心的配置文件,那么加載這兩個(gè)配置文件的方式有兩種!* 主配置文件中包含其他的配置文件:<import resource="applicationContext2.xml"/>* 工廠創(chuàng)建的時(shí)候直接加載多個(gè)配置文件:ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml","applicationContext2.xml");

    -------------------------------------------- 來看一個(gè)屬性注入比較全的配置文件 ----------------------------------------------

    <?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:p="http://www.springframework.org/schema/p"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 使用bean標(biāo)簽 --><bean id="userService" class="com.itheima.demo2.UserServiceImpl"><property name="name" value="小鳳"/></bean><!-- 演示的依賴注入 --><bean id="customerDao" class="com.itheima.demo3.CustomerDaoImpl"/><bean id="customerService" class="com.itheima.demo3.CustomerServiceImpl"><property name="customerDao" ref="customerDao"/></bean><!-- 演示的構(gòu)造方法的注入的方式 --><bean id="car1" class="com.itheima.demo4.Car1"><!-- <constructor-arg name="cname" value="奇瑞QQ"/><constructor-arg name="price" value="25000"/> --><constructor-arg index="0" value="囚車"/><constructor-arg index="1" value="545000"/></bean><!-- 演示的依賴注入 --><bean id="person" class="com.itheima.demo4.Person"><constructor-arg name="pname" value="美美"/><constructor-arg name="car1" ref="car1"/></bean><!-- 采用set方法注入<bean id="car2" class="com.itheima.demo4.Car2"><property name="cname" value="二八自行車"/><property name="price" value="1000"/></bean> --><!-- 采用p名稱空間注入的方式(了解) <bean id="car2" class="com.itheima.demo4.Car2" p:cname="保時(shí)捷" p:price="1000000"/>--><!-- 使用SPEL方式注入 --><bean id="car2" class="com.itheima.demo4.Car2"><property name="cname" value="#{'福特野馬'}"/><property name="price" value="#{450000}"/></bean><!-- 注入集合 <bean id="user" class="com.itheima.demo4.User"><property name="arrs"><list><value>哈哈</value><value>呵呵</value><value>嘿嘿</value></list></property><property name="list"><list><value>美美</value><value>小鳳</value></list></property><property name="map"><map><entry key="aaa" value="小蒼"/><entry key="bbb" value="小澤"/></map></property><property name="pro"><props><prop key="username">root</prop><prop key="password">1234</prop></props></property></bean>--><!-- 引入其他的配置文件 <import resource="applicationContext2.xml"/>--> </beans>

    四、在web項(xiàng)目中集成Spring

    CustomerDao.java:

    public interface CustomerDao {public void save(); }

    CustomerDaoImpl.java:

    public class CustomerDaoImpl implements CustomerDao {public void save() {System.out.println("持久層:保存客戶...");} }

    CustomerService.java:

    public interface CustomerService {public void save(); }

    CustomerServiceImpl.java:

    public class CustomerServiceImpl implements CustomerService {private CustomerDao customerDao;public void setCustomerDao(CustomerDao customerDao) {this.customerDao = customerDao;}public void save() {System.out.println("業(yè)務(wù)層:保存客戶...");cust omerDao.save();} }

    配置文件 applicationContext.xml 添加如下:

    <!-- 配置客戶的業(yè)務(wù)層 --> <bean id="customerService" class="com.itheima.service.CustomerServiceImpl"><property name="customerDao" ref="customerDao"/> </bean><!-- 配置持久層 --> <bean id="customerDao" class="com.itheima.dao.CustomerDaoImpl"/>

    CustomerAction.java:

    /*** 客戶的Action* @author Administrator*/ public class CustomerAction extends ActionSupport{private static final long serialVersionUID = 113695314694166436L;/*** 保存客戶* @return*/public String save(){System.out.println("WEB層:保存客戶...");// 使用工廠/*ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");CustomerService cs = (CustomerService) ac.getBean("customerService");cs.save();*/ServletContext servletContext = ServletActionContext.getServletContext();// 需要使用WEB的工廠的方式WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);CustomerService cs = (CustomerService) context.getBean("customerService");cs.save();return NONE;} }

    頁面每次點(diǎn)擊保存客戶,則會(huì)調(diào)用 Action 層(WEB層) save() 方法,再調(diào)用 Service 層(業(yè)務(wù)層),最后調(diào)用 Dao 層(持久層)。

    但這里會(huì)出現(xiàn)一個(gè)問題,每訪問一次都會(huì)加載一次配置文件(即每次請求都會(huì)創(chuàng)建一個(gè)工廠類,服務(wù)器端的資源就浪費(fèi)了,一般情況下一個(gè)工程只有一個(gè)Spring的工廠類就OK了)。需要解決該問題,該怎么解決呢?整合來了。

    第一步:找到spring-framework-4.2.4.RELEASE\libs\spring-web-4.2.4.RELEASE.jar復(fù)制到 WEB-INF\lib 目錄(即導(dǎo)入該 jar 包);

    第二步:得先溫故 Servlet 監(jiān)聽器有關(guān)知識(shí)了,如圖

    • 有這么一類監(jiān)聽器,監(jiān)聽 ServletContext 對象的創(chuàng)建和銷毀的。

    • ServletContext 對象什么時(shí)候創(chuàng)建?當(dāng)服務(wù)器啟動(dòng)時(shí)候創(chuàng)建,當(dāng)服務(wù)器銷毀時(shí)候關(guān)閉。

    當(dāng)服務(wù)器啟動(dòng), ServletContext 對象創(chuàng)建,則監(jiān)聽器對象的方法執(zhí)行,加載 applicationContext.xml 文件,而且只會(huì)加載一次,并且里面的那些對象已經(jīng)創(chuàng)建好了。

    第三步:配置監(jiān)聽器(在 web.xml 添加如下)

    <!-- 配置WEB整合的監(jiān)聽器 --> <listener><!-- 服務(wù)器一啟動(dòng),監(jiān)聽器這個(gè)類的方法就會(huì)執(zhí)行,可以關(guān)聯(lián)查看源碼 --> <!-- 配置該監(jiān)聽器是固定的,只需要每次粘貼過來就行。--><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加載方式:該監(jiān)聽器默認(rèn)加載WEB-INF目錄下的配置文件。--> <!-- 我們提供配置方式,加載其他目錄下配置文件,如src目錄下的配置文件 --> <context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value> </context-param>

    第四步:編寫 Servlet

    public String save(){System.out.println("WEB層:保存客戶...");ServletContext servletContext = ServletActionContext.getServletContext();// 需要使用WEB的工廠的方式WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);CustomerService cs = (CustomerService) context.getBean("customerService");cs.save();return NONE; }

    步驟小結(jié):Spring框架整合WEB(不是最終的方案)

    1. 創(chuàng)建JavaWEB項(xiàng)目,引入Spring的開發(fā)包。編寫具體的類和方法。* 環(huán)境搭建好后,啟動(dòng)服務(wù)器來測試項(xiàng)目,發(fā)送每訪問一次都會(huì)加載一次配置文件,這樣效率會(huì)非常非常慢!!2. 解決上面的問題* 將工廠創(chuàng)建好了以后放入到ServletContext域中.使用工廠的時(shí)候,從ServletContext中獲得.* ServletContextListener:用來監(jiān)聽ServletContext對象的創(chuàng)建和銷毀的監(jiān)聽器.* 當(dāng)ServletContext對象創(chuàng)建的時(shí)候:創(chuàng)建工廠 , 將工廠存入到ServletContext3. Spring整合Web項(xiàng)目* 引入spring-web-4.2.4.RELEASE.jar包* 配置監(jiān)聽器<!-- 配置Spring的核心監(jiān)聽器: --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param>4. 修改servlet的代碼* 從ServletContext中獲得工廠* 具體代碼如下ServletContext servletContext = ServletActionContext.getServletContext();// 需要使用WEB的工廠的方式WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);CustomerService cs = (CustomerService) context.getBean("customerService");cs.save();

    參考:《2017黑馬java基礎(chǔ)班+就業(yè)班》視頻

    總結(jié)

    以上是生活随笔為你收集整理的Spring学习笔记1的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。