Spring讀取配置檔案的點點滴滴

2021-06-13 21:53:10 字數 3411 閱讀 1942

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(

//new fileinputstream("d:\\ncode\\mcode\\sday02\\src\\spring.xml"));

factory= 

newxmlbeanfactory(resource); 

//xmlbeanfactory(引數可以是

resource

或者filesystemresource

等//但是不能是 

res 

原因可以檢視:文件

part iii. core technologies 6. resources

//中6.2 the resource inte***ce 

有關isopen

方法的說明

);factory = 

new"spring.xml"

);  

//從類路徑中載入

factory = 

new

"d:\\ncode\\mcode\\sday02\\src\\spring.xml"

); //從檔案系統載入

helloservice helloservice = 

factory.getbean(

"helloserviceimpl"

, helloserviceimpl.

class);

helloservice.sayhello();

使用2、

應用上下文

:建立在

bean

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

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

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

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

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

bean

傳送事件。

在很少的情況下,使用

beanfactory

,如在移動裝置。

new"file:d:\\ncode\\mcode\\sday02\\src\\spring.xml");

context = 

new

"classpath:spring.xml");

helloservice helloservice =

context.getbean(

"helloserviceimpl"

, helloserviceimpl.

class);

helloservice.sayhello();

使用3、在

web應用程式中

1、採用

物件 初始化容器

new//預設的路徑

//重新設定路徑

//設定

servletcontext

上下下文為

web應用程式的上下文

context.setservletcontext(getservletcontext());

//重新整理

context.refresh();

//根據id

名稱獲取

hellodao hellodao = context.getbean(

"hellodaoimpl"

, hellodaoimpl.

class);

//執行

hellodao

物件的方法

hellodao.sayhello();

預設載入的檔案和檔名稱為:

因此需要在

web-inf

下新增此配置檔案。

2、利用 

工具類//

直接採用

context物件

//context = 

system.

out.println(context);

hellodao hellodao = context.getbean(

"hellodaoimpl"

, hellodaoimpl.

class);

hellodao.sayhello();

說明: 1

、當採用

context

物件的時候,輸出的

context

物件為null  

所以在使用

context.getbean(

"hellodaoimpl"

, hellodaoimpl.

class

);會出現空指標的異常

2、當採用

context

物件的時候 會出現如下

bug

bug解決:不關是1和

2都是因為沒有在

web.xml

檔案中配置

contextloaderlistener,

所以只需要在

web.xml

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

<

context-param

>

<

param-name

>

contextconfiglocation

param-name

>

<

param-value

>

param-value

>

context-param

>

<

listener

>

<

listener-class

>

org.springframework.web.context.contextloaderlistener

listener-class

>

listener

>

Spring讀取配置檔案的點點滴滴

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

spring讀取配置檔案

一般來說。我們會將一些配置的資訊放在。properties檔案中。然後使用 將配置檔案中的資訊讀取至spring的配置檔案。那麼我們如何在spring讀取properties檔案呢。1.首先。我們要先在spring配置檔案中。定義乙個專門讀取properties檔案的類.例 classpath jd...

spring讀取配置檔案的幾種方式

場景 假如有以下屬性檔案dev.properties,需要注入下面的tag tag 123 通過propertyplaceholderconfigurer value private string tag 通過preferencesplaceholderconfigurer value privat...