zoukankan      html  css  js  c++  java
  • spring getbean 方法分析(很实用!)

    在最近的项目中,有个地方我们不得不实用getBean的方法,自己从Spring context中获取bean进行数据库操作。

    方法一(效率低,极易出现bug,不推荐使用):

    刚刚开始的时候,我们使用这中方式,但是在应用过程中发现此方式效率低下,而且极易出现bug。 在我们系统中会生成ehcache_auto_created_时间戳文件夹,

    <!-- lang: java -->
    String[] xmlCfg = new String[] {"classpath:/spring/applicationContext-service.xml",
    			"classpath:/spring/applicationContext-util.xml",
    			"classpath:/spring/applicationContext.xml"}; 
    ApplicationContext context  = new FileSystemXmlApplicationContext(xmlCfg);
    // 获取inspectionUtil bean
    inspectionUtil = (InspectionUtil) context.getBean("inspectionUtil");
    

    所以我google了一下,改用其他方法。

    方法二(效率高,灵活性高,可复用,推荐使用): 创建一个工具类SpringContextsUtil ,通过实现Spring中的ApplicationContextAware接口,在applicationContext.xml中注入bean后Spring会自动调用setApplicationContext方法。此时我们就可以获取到Spring context。

    <!-- lang: java -->
    public class SpringContextsUtil implements ApplicationContextAware{
    

    private static ApplicationContext applicationContext; //Spring应用上下文环境
    /**

    • 实现ApplicationContextAware接口的回调方法,设置上下文环境
    • @param applicationContext
    • @throws BeansException
      */
      public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      SpringContextsUtil.applicationContext = applicationContext;
      }

    /**

    • @return ApplicationContext
      */
      public static ApplicationContext getApplicationContext() {
      return applicationContext;
      }

    /**

    • 获取对象
    • @param name
    • @return Object 一个以所给名字注册的bean的实例
    • @throws BeansException
      */
      public static Object getBean(String name) throws BeansException {
      return applicationContext.getBean(name);
      }

    /**

    • 获取类型为requiredType的对象
    • 如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
    • @param name bean注册名
    • @param requiredType 返回对象类型
    • @return Object 返回requiredType类型对象
    • @throws BeansException
      */
      public static Object getBean(String name, Class requiredType) throws BeansException {
      return applicationContext.getBean(name, requiredType);
      }

    /**

    • 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
    • @param name
    • @return boolean
      */
      public static boolean containsBean(String name) {
      return applicationContext.containsBean(name);
      }

    /**

    • 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
    • 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
    • @param name
    • @return boolean
    • @throws NoSuchBeanDefinitionException
      */
      public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
      return applicationContext.isSingleton(name);
      }

    /**

    • @param name
    • @return Class 注册对象的类型
    • @throws NoSuchBeanDefinitionException
      */
      public static Class getType(String name) throws NoSuchBeanDefinitionException {
      return applicationContext.getType(name);
      }

    /**

    • 如果给定的bean名字在bean定义中有别名,则返回这些别名
    • @param name
    • @return
    • @throws NoSuchBeanDefinitionException
      */
      public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
      return applicationContext.getAliases(name);
      }
      }

调用方法:

<!-- lang: java -->
// 获取inspectionUtil bean
inspectionUtil = (InspectionUtil) SpringContextUtil.getBean("inspectionUtil");

注:

1、使用时会出现无法获取applicationContext,并抛出NullPointerException。 原因:使用此方法必须在spring applicationContext.xml中注入bean。否则spring无法自动调用setApplicationContext。如下

<!-- lang: xml -->
<bean id="springContextsUtil" class="com.sinosoft.sepmis.util.SpringContextsUtil" ></bean>

2、如果注入后仍然出现这个问题。 则修改<beans default-autowire="byName" default-lazy-init="true">中的default-lazy-init="false"。 或者是修改bean注入属性

<!-- lang: xml -->
<bean id="springContextsUtil" class="com.sinosoft.sepmis.util.SpringContextsUtil" lazy-init="false"></bean>
                                                <div class="ad-wrap" style="margin-top: 12px;">
                                                    <div data-traceid="blog_down_1" data-tracepid="blog_down" style="text-align:center">
<!-- oschina-blog-728x90 -->
<ins class="adsbygoogle" style="display:inline-block;728px;height:90px" data-ad-client="ca-pub-7090564139599510" data-ad-slot="5590362768"></ins>
<script>
    (adsbygoogle = window.adsbygoogle || []).push({});
</script>
<script type="text/javascript">
    function googleAdJSAtOnload() {
        var element = document.createElement("script");
        element.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
        element.async = true;
        document.body.appendChild(element);
    }
    if (window.addEventListener) {
        window.addEventListener("load", googleAdJSAtOnload, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", googleAdJSAtOnload);
    } else {
        window.onload = googleAdJSAtOnload;
    }
</script>
查看全文
  • 相关阅读:
    JSON格式
    多行写入
    文件对象write() and read()
    一个虚拟摄像头Filter(Virtual Cam Capture Filter)
    五十种最好的开源爬虫
    web scraper 里的 Element click 模拟点击「加载更多」
    介绍一款好用又易学的爬虫工具:web scraper
    安装宝塔面板后 ,centos系统 挂载硬盘 或者 数据盘和系统盘合并
    帝国CMS恢复搜索功能 增加搜索数据源设置教程
    安装帝国CMS步骤 和恢复数据
  • 原文地址:https://www.cnblogs.com/jpfss/p/9453794.html
  • Copyright © 2011-2022 走看看