Spring容器初始化及問題解決方案
1.Spring bean組件 ”默認為單例模式scope=“singleton, 運行JavaApplication容器啟動時自動創(chuàng)建對象
scope=“prototype”為多例模式,請求條件下才創(chuàng)建對象
2beans組件 里面default-init-method初始化方法加載,范圍比較大,當沒有此方法時不會報錯,default-destroy-method銷毀方法,default-lazy-init=“true/false” 對象延時實例化
3.bean組件里面init-method初始化無此方法,會報錯, destroy-method銷毀方法,lazy-init=“true/false” 延時實例化
注意:
1.銷毀方法對scope=“prototype”多例模式無效
2.AbstractApplicationContext可以關閉容器,可以調用close()方法,關閉容器,調用銷毀方法
3.對象延時實例化對多例模式沒有意義。
XML
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" 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" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd" default-init-method="initEmp" default-destroy-method="destroyEmp" default-lazy-init="true"> <bean id="emp" init-method="initEmp" destroy-method="destroyEmp" lazy-init="false" class="com.tracy.bean.Emp" scope="singleton" ></bean> </beans>
Test方法
//bean組件的默認方式
@Test
public void beanInitTest() {
AbstractApplicationContext appContext=new ClassPathXmlApplicationContext("com/tracy/xml/bean-init-destroy.xml");
ApplicationContext app=new ClassPathXmlApplicationContext("com/tracy/xml/bean-init-destroy.xml");
Emp emp=app.getBean("emp",Emp.class);
System.out.print(emp);
appContext.close();
}
通過構造完成初始bean屬性,可以通過初始化完成
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot中Elasticsearch的連接配置原理與使用詳解
Elasticsearch是一種開源的分布式搜索和數據分析引擎,它可用于全文搜索、結構化搜索、分析等應用場景,本文主要介紹了SpringBoot中Elasticsearch的連接配置原理與使用詳解,感興趣的可以了解一下2023-09-09
基于MybatisPlus插件TenantLineInnerInterceptor實現多租戶功能
這篇文章主要介紹了基于MybatisPlus插件TenantLineInnerInterceptor實現多租戶功能,需要的朋友可以參考下2021-11-11
springboot斷言異常封裝與統(tǒng)一異常處理實現代碼
異常處理其實一直都是項目開發(fā)中的大頭,但關注異常處理的人一直都特別少,下面這篇文章主要給大家介紹了關于springboot斷言異常封裝與統(tǒng)一異常處理的相關資料,需要的朋友可以參考下2023-01-01
Mybatis/Mybatis-Plus駝峰式命名映射的實現
本文主要介紹了Mybatis-Plus駝峰式命名映射的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07

