国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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

2019-11-14 20:50:54
字體:
來源:轉載
供稿:網友
在普通類中獲取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')的靜態方法得到springbean對象


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 北京市| 龙陵县| 靖江市| 昭觉县| 龙井市| 普兰店市| 福建省| 安西县| 巴青县| 区。| 大悟县| 双鸭山市| 板桥市| 阳江市| 贺兰县| 科尔| 龙井市| 林口县| 大英县| 宜城市| 陇西县| 牟定县| 广南县| 桦南县| 青冈县| 屯门区| 阳谷县| 静乐县| 洛扎县| 卫辉市| 武强县| 汶川县| 神农架林区| 南平市| 永登县| 鄂伦春自治旗| 无锡市| 监利县| 新化县| 湄潭县| 夹江县|