spring讀取配置檔案初始化容器操作總結

2021-07-24 13:02:38 字數 2739 閱讀 4599

spring

初始化容器

.三種經常用到的實現:

從類路徑中載入。

從檔案系統載入。 從

web系統中載入。

使用1、bean工廠:

最簡單的容器,提供了基礎的依賴注入支援。建立各種型別的

bean.

beanfactory factory = null; 

//宣告

classpathresource resource = newclasspathresource("spring.xml");

//類路徑

filesystemresource 

filesystemresource=

newfilesystemresource("d:\\ncode\\mcode\\sday02\\src\\spring.xml"); 

//系統路徑

//inputstreamresource res 

//= new inputstreamresource(

//newfileinputstream("d:\\

ncode

\\mcode

\\sday02\\

src\\spring.xml"));

factory= new

xmlbeanfactory(resource); 

//xmlbeanfactory(引數可以是resource或者filesystemresource等

//但是不能是 res 原因可以檢視:文件part iii. core technologies 6. resources

//中6.2 the resource inte***ce 有關isopen方法的說明);

//從類路徑中載入

factory = new

//從檔案系統載入

helloservice helloservice = 

factory.getbean("helloserviceimpl", helloserviceimpl.class);

helloservice.sayhello();

使用2、

應用上下文:

建立在bean

工廠基礎之上,提供系統架構服務。

更加高階的容器。功能強大:

1.提供文字資訊解析工具,包括對國際化支援。

2.提供載入檔案資源的通用方法,如。

3.可以向註冊為***的

bean

傳送事件。

在很少的情況下,使用beanfactory

,如在移動裝置。

context = new

helloservice helloservice =

context.getbean("helloserviceimpl", helloserviceimpl.class);

helloservice.sayhello();

使用3、在web

應用程式中

物件 初始化容器

//重新設定路徑

//    

//設定

servletcontext

上下下文為

web應用程式的上下文

context.setservletcontext(getservletcontext());

//重新整理

context.refresh();

//根據

id名稱獲取

hellodao hellodao = context.getbean("hellodaoimpl", hellodaoimpl.class);

//執行

hellodao

物件的方法

hellodao.sayhello();

因此需要在web-inf

下新增此配置檔案。

//直接採用

(getservletcontext())

獲取context物件

(getservletcontext());

//context = 

//system.out.println(context);

hellodao hellodao = context.getbean("hellodaoimpl", hellodaoimpl.class);

hellodao.sayhello();

說明:1、當採用

(getservletcontext())

獲取context

物件的時候,輸出的

context

物件為null  

所以在使用

context.getbean("hellodaoimpl", hellodaoimpl.class);

會出現空指標的異常

2、當採用

物件的時候 會出現如下

bug

bug解決:

不關是1和2

都是因為沒有在

web.xml

檔案中配置

contextloaderlistener

,所以只需要在

web.xml

檔案中加入以下**中即可

contextconfiglocation

param-name>

param-value>

context-param>

org.springframework.web.context.contextloaderlistener

listener-class>

listener>

spring讀取配置檔案初始化容器操作

spring初始化容器 三種經常用到的實現 從類路徑中載入。從檔案系統載入。從web 系統中載入。使用1 bean工廠 最簡單的容器,提供了基礎的依賴注入支援。建立各種型別的 bean.beanfactory factory null 宣告 classpathresource resource ne...

MySQL 初始化讀取配置檔案摘要

摘自 mysql技術內幕 innodb儲存引擎 在資料庫例項啟動時,會在以下位置讀取配置檔案 etc my.cnf etc mysql my.cnf usr local mysql etc my.cnf mycnf 讀取順序 由 前 到後 依次讀取 如存在多個配置檔案,以最後讀取的配置檔案為準。my...

mysql 初始化配置檔案 MySQL 初始化配置

1 方式 原始碼安裝 編譯過程中設定初始化引數 配置檔案 資料庫啟動之前,設定配置檔案引數 etc my.cnf 啟動指令碼命令列 mysqld safe skip grant tables skip networking 說明 my.cnf port 3306 mysqld safe port 3...