DIV CSS 佈局教程網

Java 中獲取 Spring 配置 Bean 的五種方式
編輯:關於JavaScript     

Spring 是一個輕量級的控制反轉(IoC)與面向切面(AOP)容器框架。在我們需要於程序各處取用容器中的 Bean 時,有五種常見做法,下面逐一介紹。

方法一:初始化時保存 ApplicationContext 對象

ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml");
ac.getBean("beanId");

這種方式適用於採用 Spring 框架的獨立應用程序,需要程序通過配置文件手工初始化 Spring 的情況。

方法二:通過工具類獲取 ApplicationContext

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");

方法三:繼承 ApplicationObjectSupport

該抽象類提供 getApplicationContext() 方法,可方便地拿到 ApplicationContext。Spring 初始化時,會通過 setApplicationContext(ApplicationContext context) 方法把對象注入進來。

方法四:繼承 WebApplicationObjectSupport

類似方法三,調用 getWebApplicationContext() 獲取 WebApplicationContext。

方法五:實現 ApplicationContextAware 接口

實現該接口的 setApplicationContext(ApplicationContext context) 方法並保存下來,Spring 初始化時會自動通過該方法注入 ApplicationContext 對象。

總體來說,Web 環境下推薦用工具類或 Aware 接口的方式解耦,獨立應用則可手工初始化後直接使用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved