獲取Spring中的bean有很多種方式,再次總結一下:
第一種:在初始化時保存ApplicationContext對象
1
2
|
ApplicationContext ac = new FileSystemXmlApplicationContext( "applicationContext.xml" ); ac.getBean( "beanId" ); |
說明:這種方式適用于采用Spring框架的獨立應用程序,需要程序通過配置文件手工初始化Spring。
第二種:通過Spring提供的工具類獲取ApplicationContext對象
1
2
3
4
5
|
import org.springframework.web.context.support.WebApplicationContextUtils; ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); ac1.getBean( "beanId" ); ac2.getBean( "beanId" ); |
說明:
1、這兩種方式適合于采用Spring框架的B/S系統,通過ServletContext對象獲取ApplicationContext對象,然后在通過它獲取需要的類實例;
2、第一種方式在獲取失敗時拋出異常,第二種方式返回null。
第三種:繼承自抽象類ApplicationObjectSupport
說明:通過抽象類ApplicationObjectSupport提供的getApplicationContext()方法可以方便的獲取到ApplicationContext實例,進而獲取Spring容器中的bean。Spring初始化時,會通過該抽象類的setApplicationContext(ApplicationContext context)方法將ApplicationContext 對象注入。
第四種:繼承自抽象類WebApplicationObjectSupport
說明:和上面方法類似,通過調用getWebApplicationContext()獲取WebApplicationContext實例;
第五種:實現接口ApplicationContextAware
說明:實現該接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext對象。Spring初始化時,會通過該方法將ApplicationContext對象注入。
雖然Spring提供了后三種方法可以實現在普通的類中繼承或實現相應的類或接口來獲取Spring的ApplicationContext對象,但是在使用時一定要注意繼承或實現這些抽象類或接口的普通java類一定要在Spring的配置文件(即application-context.xml文件)中進行配置,否則獲取的ApplicationContext對象將為null。
下面通過實現接口ApplicationContextAware的方式演示如何獲取Spring容器中的bean:
首先自定義一個實現了ApplicationContextAware接口的類,實現里面的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
package com.ghj.tool; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringConfigTool implements ApplicationContextAware { // extends ApplicationObjectSupport{ private static ApplicationContext ac = null ; private static SpringConfigTool springConfigTool = null ; public synchronized static SpringConfigTool init() { if (springConfigTool == null ) { springConfigTool = new SpringConfigTool(); } return springConfigTool; } public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { ac = applicationContext; } public synchronized static Object getBean(String beanName) { return ac.getBean(beanName); } } |
其次在applicationContext.xml文件進行配置:
最后通過如下代碼就可以獲取到Spring容器中相應的bean了:
注意一點,在服務器啟動Spring容器初始化時,不能通過以下方法獲取Spring容器:
1
2
3
4
5
|
import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); wac.getBean(beanID); |
以上就是本文的全部內容,希望對大家的學習有所幫助。