在普通類中獲取Spring管理的bean


  1、在項目中添加下面的類:

  

import org.springframework.context.ApplicationContext;  
import org.springframework.context.ApplicationContextAware;  
/** 
 * 以靜態變量保存Spring ApplicationContext, 可在任何代碼任何地方任何時候中取出ApplicaitonContext. 
 *  
 */  
public class SpringContextHolder implements ApplicationContextAware {  
private static ApplicationContext applicationContext;  
  
/** 
* 實現ApplicationContextAware接口的context注入函數, 將其存入靜態變量. 
*/  
public void setApplicationContext(ApplicationContext applicationContext) {  
SpringContextHolder.applicationContext = applicationContext; // NOSONAR  
}  
  
/** 
* 取得存儲在靜態變量中的ApplicationContext. 
*/  
public static ApplicationContext getApplicationContext() {  
checkApplicationContext();  
return applicationContext;  
}  
  
/** 
* 從靜態變量ApplicationContext中取得Bean, 自動轉型為所賦值對象的類型. 
*/  
@SuppressWarnings("unchecked")  
public static <T> T getBean(String name) {  
checkApplicationContext();  
return (T) applicationContext.getBean(name);  
}  
  
/** 
* 從靜態變量ApplicationContext中取得Bean, 自動轉型為所賦值對象的類型. 
*/  
@SuppressWarnings("unchecked")  
public static <T> T getBean(Class<T> clazz) {  
checkApplicationContext();  
return (T) applicationContext.getBeansOfType(clazz);  
}  
  
/** 
* 清除applicationContext靜態變量. 
*/  
public static void cleanApplicationContext() {  
applicationContext = null;  
}  
  
private static void checkApplicationContext() {  
if (applicationContext == null) {  
throw new IllegalStateException("applicaitonContext未注入,請在applicationContext.xml中定義SpringContextHolder");  
}  
}  
}  

  2、在spring配置文件中加入:

<bean class="com.xxxxx.SpringContextHolder" lazy-init="false" />  

  3、使用方法:

  SpringContextHolder.getBean('xxxx')的靜態方法得到spring bean對象 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM