前言:去年到現在一直沒有很好的時間完成這個spring基礎+原始碼的博客目標,去年一年比較懶吧,所以今年我希望我的知識可以分享給正在奮斗中的互聯網開發人員,以及未來想往架構師上走的道友們我們一起進步,從一個互聯網職場小白到一個滬漂濕人,一路讓我知道分享是一件多么重要的事情,總之不對的地方,多多指出,我們一起徜徉代碼的海洋!
我這里做每個章節去說的前提,不是一定很標準的套用一些官方名詞,目的是為了讓大家可以理解更加清楚,如果形容的不恰當,可以留言出來,萬分感激
1、如何控制簡單物件的創建次數
上節我們提到了,我們要是創建復雜物件,需要實作了FactoryBean介面,如果isSingleton回傳為true,說明只需要創建一次,如果為false,就需要創建多次復雜物件,每個物件都不同!
我們定義一個Account類并在xml中這么寫
<!-- 如果我們想對這個簡單物件,控制次數,加個scope標簽,為singleton,那么這個scope物件只會被創建一次--> <bean id="account" scope="singleton" class="com.chenxin.spring5.scope.Account"></bean>如果scope為singleton,說明只創建一次,這個標簽默認不寫,就是默認只創建一次,所以Spring默認給我們的物件創建都是singleton(單例),如果是prototype,則是創建多次不同的物件
<!-- 如果我們想對這個簡單物件,控制次數,加個scope標簽并且等于prototype,那么這個scope物件只會被創建多次--> <bean id="account" scope="prototype" class="com.chenxin.spring5.scope.Account"></bean>2、如何控制復雜物件創建次數
我們要是創建復雜物件,需要實作了FactoryBean介面,如果isSingleton回傳為true,說明只需要創建一次,如果為false,就需要創建多次復雜物件
那會有同學問,如果是實體工廠或者靜態工廠,他們沒實作isSingleton方法,他們其實還是以scope的方式來控制物件的創建次數!
3、為什么我們要控制物件創建次數
因為有些物件能被共用,那么就只需要創建一次就可以了;有些物件不能被大家共用,所以我們要把這個物件管理起來,根據這個物件的自身特點,來進行創建條件
好處:節省不必要的資源浪費
- 什么樣的物件只需要創建一次
1、SqlSessionFactory
2、DAO(因為你插入資料,我也插入資料,我們都是insert方法,我們沒有區別)
3、Service(你登錄我也要登錄,我們之間的差異是在用戶名或者其他在入參的不同,但是方法都是同一個,做一樣的事情)
- 什么樣的物件需要創建新的
1、Connection
2、Sqlsession、Session會話
3、Struts2 Action
4、物件的生命周期
1、什么是物件的什么周期
指的是一個物件的創建,存活,消亡的一個完整程序
2、為什么要學習物件的生命周期
我們知道一開始對于物件的創建, 是通過new來創建的,這個物件在一直被參考的情況下,會一直存活在虛擬機中,由我們代碼和虛擬機一起,管理這個物件的生命周期
那么今天講的這個物件的存活和消亡程序,不是由我們來控制了,而是交給Spring去控制,如果我們更加了解物件的生命周期,實際上我們會更好利用Spring為我們創建好的物件來為我們做事情
3、生命周期的三個階段
- 創建階段
Spring工廠何時幫我們創建物件?分情況
1、如果物件只被創建一次,也就是scope="singleton"的時候,Spring工廠創建的同時,物件會同時創建出來
2、如果物件被創建多次,也就是scope="prototype"的時候,Spring工廠會獲取物件(ctx.getBean)的同時,創建物件
如果被創建一次:
<bean id="account" class="com.chenxin.spring5.Account"> </bean>物體類
public class Account { private Integer id; private String name; public Account() { System.out.println("Account.Account"); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + '}'; } }測驗,如果scope="singleton"或者bean這個scope標簽不寫的時候,默認物件只創建一次,那么在工廠被new出來的時候,一定是會呼叫構造方法進行物件的創建的
@Test public void test1(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml"); // Account account = (Account) ctx.getBean("account"); // System.out.println("account = " + account); }Account.Account如果是scope="prototype",那么物件會創建多次,則會在getBean的時候,工廠才會幫我們把物件創建,
<bean id="account" scope="prototype" class="com.chenxin.spring5.Account"> </bean>@Test public void test1(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml"); Account account = (Account) ctx.getBean("account"); // System.out.println("account = " + account); }所以可以很清楚了解到工廠何時幫我們創建物件的情況,
那加入我此時,scope="singleton",但是我不想在工廠創建的時候,幫我們創建,物件,我需要在getBean的時候,來創建物件,這回怎么搞呢?
那我們這么來,我們只需要加個標簽lazy-init="true",表示懶加載
<bean id="account" scope="prototype" class="com.chenxin.spring5.Account" lazy-init="true"> </bean>這樣的話我們就可以在singleton前提下,再呼叫getBean時候, 工廠才會開始幫我們創建物件!
- 初始化階段
什么是初始化階段呢?
指的是Spring工廠在創建完物件后,呼叫物件的初始化方法,完成對應的初始化操作!
1、初始化誰來提供呢:程式員根據需求,提供初始化方法,完成初始化操作,
2、初始化方法是誰呼叫:Spring工廠來進行呼叫
Spring為初始化提供了兩種途徑:
1、InitializingBean介面:需要實作InitializingBean的afterPropertiesSet()這個方法,完成初始化操作的代碼,可以寫在這個方法中;因為你實作的是Spring介面,所以Spring就可以找到你實作的介面,并且可以找到這個方法;
public class Product implements InitializingBean { public Product() { System.out.println("Product.Product"); } /* * 這個就是初始化方法:做一些初始化的操作 * Spring會進行呼叫 */ public void afterPropertiesSet() throws Exception { System.out.println("Product.afterPropertiesSet"); } }<bean id="product" class="com.chenxin.spring5.Product"></bean>@Test public void test2(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml"); }所以輸出結果是先創建物件,呼叫了構造方法,Spring再進行物件的初始化,發現要初始化的時候,我實作了這個InitializingBean介面的afterPropertiesSet方法,進而會幫我們呼叫初始化方法進行初始化
但是這里有個問題,看過上一章節的同學可以知道,這個InitializingBean類似FactoryBean介面,都是耦合了Spring的框架,對代碼擴展性很不好,如果我離開了Spring框架,也就以為著這些初始化代碼,就無法可以繼續使用了,所以我們對初始化為了靈活,我們會有另一個策略;
2、類中提供一個普通的方法
public class Cat { public Cat() { System.out.println("Cat.Cat"); } /** * 提供一個普通方法 */ public void myInit(){ System.out.println("Cat.myInit"); } }要想讓Spring知道你這個初始化方法的呼叫,是不是只能在組態檔里告知Spring你要呼叫我這個初始化方法,這樣我可以不用你的InitializingBean介面了,即便后期你換了其他的框架,你代碼依舊是可以用,起碼不會報錯can not find InitializingBean
<bean id="cat" class="com.chenxin.spring5.Cat" init-method="myInit"></bean>Cat.Cat Cat.myInit這樣就可以更加靈活控制物件的初始化了!
細節分析:
如果一個物件既實作了InitializingBean,同時又提供了普通的初始化方法myInit(),執行順序是什么呢?我們測驗下
public class Product implements InitializingBean {//不僅實作了InitializingBean public Product() { System.out.println("Product.Product"); } //還提供了普通的初始化方法 public void myInit(){ System.out.println("Product.myInit"); } /* * 這個就是初始化方法:做一些初始化的操作 * Spring會進行呼叫 */ public void afterPropertiesSet() throws Exception { System.out.println("Product.afterPropertiesSet"); } }組態檔也做了初始化方法的指向
<bean id="product" class="com.chenxin.spring5.Product" init-method="myInit"></bean>結果是:
Product.Product Product.afterPropertiesSet Product.myInit很明顯,afterPropertiesSet初始化執行在自定義初始化myInit前;
所以我們知道物件在創建完后,會呼叫初始化方法;此時我們還忽略了一些細節,如果這個時候需要注入屬性,那你說這個注入操作,又是應該在物件創建之后,是先進行注入呢,還是先進行初始化操作呢?
我們測驗下
public class Product implements InitializingBean { private String name; public void setName(String name) { System.out.println("Product.setName"); this.name = name; } public Product() { System.out.println("Product.Product"); } public void myInit(){ System.out.println("Product.myInit"); } /* * 這個就是初始化方法:做一些初始化的操作 * Spring會進行呼叫 */ public void afterPropertiesSet() throws Exception { System.out.println("Product.afterPropertiesSet"); } }<bean id="product" class="com.chenxin.spring5.Product" init-method="myInit"> <property name="name" value="chenxin"></property> </bean>我們代碼在set的方法加了一句話setName
Product.Product Product.setName Product.afterPropertiesSet Product.myInit所以很明顯,set注入是在創建物件后,初始化之前,所以是創建物件->屬性注入->初始化
其實,你發現這個初始化介面afterPropertiesSet這個方法的含義就是在屬性set注入后,也表達了初始化是在set注入之前!!
那什么是初始化操作呢?
實際上是對資源的初始化,資料庫資源,io資源,網路等...所以這些功能一般情況,會在這個afterPropertiesSet里面寫
后面其實應用初始化的階段,還是比較少的!
- 銷毀階段
Spring銷毀物件前,會呼叫物件的銷毀方法,來完成銷毀操作
1、Spring在什么時候銷毀所創建的處物件呢?
ctx.close();意味著工廠關閉
銷毀方法是程式員根據自己的需求,定義銷毀方法,由Spring工廠完成呼叫!
那Spring給我們提供了哪些方法可以將物件進行銷毀呢?(其實和初始化是很像的)
1、實作DisposableBean介面
public class Product implements InitializingBean, DisposableBean { private String name; public void setName(String name) { System.out.println("Product.setName"); this.name = name; } public Product() { System.out.println("Product.Product"); } public void myInit(){ System.out.println("Product.myInit"); } /* * 這個就是初始化方法:做一些初始化的操作 * Spring會進行呼叫 */ public void afterPropertiesSet() throws Exception { System.out.println("Product.afterPropertiesSet"); } @Override public String toString() { return "Product{" + "name='" + name + '\'' + '}'; } /** * 實作銷毀方法,資源釋放的操作 * @throws Exception */ public void destroy() throws Exception { System.out.println("Product.destroy"); } }
@Test public void test3(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml"); Product product = (Product) ctx.getBean("product"); System.out.println("product = " + product); }結果你會發現,物件創建了,注入了,初始化了,但是怎么沒銷毀?
Product.Product Product.setName Product.afterPropertiesSet Product.myInit因為物件的銷毀發現在工廠關閉的時候,所以需要ctx.close(),因為close方法是在ClassPathXmlApplicationContext的父類AbstractApplicatonContext里實作的,在ApplicationContext介面沒有,所以我們要改下
@Test public void test3(){ // ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml"); ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml"); Product product = (Product) ctx.getBean("product"); System.out.println("product = " + product); ctx.close(); }結果就可以列印出銷毀方法了!
2、定義一個普通方法
我們還可以在Product中定義一個銷毀方法,叫做myDestory():
public void myDestory(){ System.out.println("Product.myDestory"); }<bean id="product" class="com.chenxin.spring5.Product" init-method="myInit" destroy-method="myDestory"> <property name="name" value="chenxin"></property> </bean>同理列印順序也是先Spring自家人,再自定義!
Product.Product Product.setName Product.afterPropertiesSet Product.myInit product = Product{name='chenxin'} Product.destroy Product.myDestory細節分析:
銷毀方法的操作只適用于scope="singleton"的方法,如果為prototype是不起任何作用的;因為物件每次都會創建新的,不知道到底你需要銷毀哪一個,所以我理解為Spring工廠索性就不幫你銷毀了,
實際上銷毀操作在開發中用的也非常少,所以大家了解下就可以了
物件生命周期總結下一張圖:
1、首先Spring工廠創建出來,檢查你bean標簽是否是單例物件還是非單例,然后再根據不同的時機(是否懶加載)開始呼叫物件的構造方法,反射來創建物件
2、創建后進行DI操作,屬性注入
3、然后開始進行初始化方法的呼叫
4、關閉工廠,呼叫銷毀方法
5、組態檔引數化
什么是組態檔引數化?指的是把Spring組態檔中需要經常修改的字串資訊,轉移到一個更小的組態檔中!
我先提出問題:
Spring組態檔中,存在經常需要修改的字串嗎?
當然存在,比如資料庫連接相關的引數,在Spring早期的時候,在applicationContext.xml中配置長達幾千行,如果關于資料庫的某個配置,在其中的某一段代碼,對于開發人員,是不是不容易知道這個情況?
好吧如果你說開發都不知道還有誰知道,那我就會覺得你接觸的業務少了,格局小啦,如果這個是給客戶的產品呢,客戶要修改某個配置,你讓他去找這些組態檔,找到具體某個配置,說我要換個資料庫配置資訊在哪里?
或者交給運維去修改,運維不懂Spring,你說他一旦改錯了,坑的是誰,還是不開發嗎?所以能不能把這個會修改的字串,轉移到一個小的組態檔中,這樣的話,是不是很方便修改和維護呢?
所以我們為了方便,我們就單獨拉出一個小的組態檔(db.properties)專門存放這個配置資訊,這個檔案你可以隨便放,我這里放在了resources下
jdbc.driverClassName = com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/users?useSSL=false jdbc.username = root jdbc.password = root那你說Spring是怎么能找到你這個組態檔呢?
我們要在xml中寫這么一段
<context:property-placeholder location="classpath:/db.properties"></context:property-placeholder><context:property-placeholder location="classpath:/db.properties"></context:property-placeholder> <bean id="conn" class="com.chenxin.spring5.factorybean.ConnectionFactoryBean"> <property name="driverName" value="${jdbc.driverClassName}"></property> <property name="url" value="${jdbc.url}"></property> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> </bean>這樣就完成了組態檔引數化的操作!后續我們想改相關的配置引數,就不需要在Spring的組態檔里改了,對吧?
6、型別轉換器
我們之前講過通過Spring組態檔,進行屬性注入,我們對于Integer屬性的值,為什么我們可以通過字串的<value></value>標簽的注入方式,來注入到Integer的屬性中呢?
其實Spring在底層幫我們完成了型別轉換,實際上就是Spring的型別轉換器(Converter介面),因為會涉及到多種型別的轉換,所以定義成介面屏蔽這個差異
所以Spring把字串給Integer的時候,是通過一個叫做StringToNumber這個型別轉換器完成的
6.1、自定義型別轉換器
當Spring內部沒有提供特定型別轉換器時,?程式員在應?的程序中還需要使?,那么就 需要程式員??定義型別轉換器
我們來試下定義一個Person類有個屬性是Date型別的
public class Person implements Serializable { private String name; private Date birthday; public void setName(String name) { this.name = name; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", birthday=" + birthday + '}'; } }xml配置
<bean id="person" class="com.chenxin.spring5.converter.Person"> <property name="name" value="chenxin"></property> <property name="birthday" value="2020-04-05"></property> </bean>測驗類:
@Test public void test4(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml"); Person person = (Person) ctx.getBean("person"); System.out.println("person = " + person); }報錯了Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birthday',說明Spring這個無法幫我們轉換字串到Date型別上,Spring沒有提供,因為日期的格式,不同的國家不同的格式,所以Spring不會轉了,這個時候我們就要自定義型別轉換器了
![]()
開發步驟:
- 類實作Converter介面
public class MyDateConverter implements Converter<String, Date> { public Date convert(String s) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = simpleDateFormat.parse(s); } catch (ParseException e) { e.printStackTrace(); } return date; } }代碼是寫完了,但是你怎么告訴Spring要找這你自己定義的型別轉換器呢? Spring肯定要先把你定義的轉換器物件交給Spring管理,創建出來,然后這個轉換器是不是要告訴Spring這不是個普通物件,這個是個轉換器,你幫我注冊到你的里面我要用來轉換
- 給Spring管理來創建
<bean id="myDateConverter" class="com.chenxin.spring5.converter.MyDateConverter"> </bean>
- 告訴Spring,你要幫我注冊到你的轉換器里面,這轉換器型別是Set集合,并且是自定義物件,需要用到ref標簽
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="myDateConverter"></ref> </set> </property> </bean>這個id,conversionService是固定,不能隨便寫;這個ConversionServiceFactoryBean中的屬性你看下,理解為什么是set標簽了吧?
這樣就可以幫我們轉換了,輸出:person = Person{name='chenxin', birthday=Sun Apr 05 00:00:00 CST 2020}
細節:
1、ConversionSeviceFactoryBean 定義 id屬性 值必須 conversionService
2、Spring框架內置?期型別的轉換器,?期格式:2020/05/01 (不?持 :2020-05-01)
7、后置處理Bean
后置處理Bean全稱是BeanPostProcessor,本次課程先入個門,后面講aop的時候,再深入講解
作用:對Spring工廠所創建的物件,進行再加工
我們來看個圖分析下:
1、對于一個User用戶,Spring創建工廠后,對掃描bean id為user,進而拿到了這個類的全路徑,然后開始反射拿到構造方法,創建物件
2、在創建物件后,注入完成,然后Spring給你留了個口子,可以你來加工下這個物件,引數Object bean表示剛創建好的物件User,而id值會交給beanName,你加工完成后,回傳了你加工好的物件
3、Spring拿到你加工好的物件,再進行初始化操作
4、初始化完成后,又給你留個口子,你又可以加工一次,再還給Spring,從而形成一個Bean
程式員實作BeanPostProcessor規定接?中的?法:
1、Object postProcessBeforeInitiallization(Object bean String beanName) 作?:Spring創建完物件,并進?注?后,可以運?Before?法進?加? 獲得Spring創建好的物件 :通過?法的引數 最終通過回傳值交給Spring框架
2、Object postProcessAfterInitiallization(Object bean String beanName) 作?:Spring執?完物件的初始化操作后,可以運?After?法進?加? 獲得Spring創建好的物件 :通過?法的引數 最終通過回傳值交給Spring框架
實戰中其實很少處理Spring的初始化操作:沒有必要區分Before After,只需要實作其中的?個After ?法即可,
開發步驟:
1、類實作BeanPostProcessor,我在處理器中修改了person.name=modify chexin
這里一定要注意,對于BeanPostProcessor來說,BeanPostProcessor會對Spring??中所有創建的物件進?加?!!!!所以你必須要判斷下是不是你想要修改的某個物件
public class MyBeanPostProcessor implements BeanPostProcessor { public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if(bean instanceof Person){ Person person = (Person) bean; person.setName("modify chenxin!"); } return bean; } }2、組態檔set name=chenxin,我們看看這個后置處理器有沒有幫我們在初始化后,修改名字?
<bean id="person" class="com.chenxin.spring5.converter.Person"> <property name="name" value="chenxin"></property> <property name="birthday" value="2020-04-05"></property> </bean> <bean id="myBeanPostProcessor" class="com.chenxin.spring5.postprocessor.MyBeanPostProcessor">結果可以試試,一定是被修改了成modify chenxin!
細節一定要注意
1、BeanPostProcessor會對Spring??中所有創建的物件進?加?!!!!所以你必須要判斷下是不是你想要修改的某個物件
2、為什么不對BeforeInitialization做操作,有個東西叫做擊鼓傳花知道不,這個程序自始至終,一定是每一個物件的流程,那你之前給我什么,我后面也一定要回傳給你什么,所以我們這里都要return bean,只是我這個案例中沒有在Before里寫而已
有興趣可以試試,正常開發,只需要實作After就可以了!
好了,本節我們講到這里,下節開始,面向Aop章節!!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/264499.html
標籤:其他
上一篇:6. 一個菱形
下一篇:21-2-20 個人筆記





