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;width: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>
spring getbean 方法分析(很实用!)的更多相关文章
- spring getbean 方法分析
spring 缺省: 1.spring用DefaultListableBeanFactory.preInstantiateSingletons()建立bean实例 2.缺省采用单例模式 在最近的项目中 ...
- 检测代理IP匿名程度的方法,很实用
做网络的基本都知道代理,这个是肯定的,不管是用花刺还是猎手的网页代理,还是直接VPN的通道代理,代理有着不用说大家也知道的重要性.不管是做CPA还是做点击亦或者投票,代理都能帮我们一下,虽然帮的忙不大 ...
- 由于开发需求需要在附件查看页面添加水印,于是网上看到一位大牛写了一个js加水印的方法觉得很实用,也很方便,记录一下,哈哈
大牛的博客链接:https://www.cnblogs.com/daixinyu/p/6715398.html 提供给大家学习 我优化了几点 1,我把水印的样式单独提出来,这样会提高渲染水印的性能 2 ...
- Spring IoC getBean 方法详解
前言 本篇文章主要介绍 Spring IoC 容器 getBean() 方法. 下图是一个大致的流程图: 正文 首先定义一个简单的 POJO,如下: public class User { priva ...
- spring容器的refresh方法分析
spring源码版本5.0.5 Spring容器创建之后,会调用它的refresh方法刷新Spring应用的上下文. 首先整体查看AbstractApplicationContext#refresh源 ...
- Spring BeanFacoty doCreateBean方法分析
上一篇,我们分析到了doCreateBean,现在继续: 先看看时序图 protected Object doCreateBean(final String beanName, final RootB ...
- 模拟Spring中的getBean方法
一直知道Spring是运用反射技术的,但具体怎么用呢?今天就模拟下getBean方法. 步骤: 1.用Dom4j解析xml配置文件,取出我们需要的信息 2.遍历Bean节点,根据每个Bean节点的cl ...
- 模拟Spring容器的getBean方法(Maven工程)
Spring容器的getBean方法是通过反射机制实现的,下面的测试程序模拟getBean的实现原理. 步骤一:pom.xml文件配置解析XML文件的dom4j.jar 步骤二:XML文件中配置bea ...
- Spring之BeanFactory:解析getBean()方法
初探getBean()方法 在使用Spring的时候可以通过如下方式调用getBean方法来获取某个Bean: User user = context.getBean(User.class); Abs ...
随机推荐
- 【Mysql】将Excel表导入至Mysql的当中一张表
如果表格有A(整型字段).B(整型字段).C(字符串数据)三列数据,希望导入到Mysql中数据库中表格table.table中须要插入的字段各自是col1,col2,col3 1.在随意一列,如果在D ...
- 6. oracle学习入门系列之六 模式
oracle学习入门系列之六 模式 上篇咱们学习记录了ORACLE数据库中的数据库结构.内存结构和进程等.篇幅 蛤蟆感觉偏多了.这次要休整下,每次笔记不宜太多,不然与书籍有何差别. 我们要保证的是每次 ...
- <memory>(包括了auto_ptr,shared_ptr等各种指针)
Memory elements This header defines general utilities to manage dynamic memory: Allocators allocator ...
- 深入理解Linux启动过程
深入理解Linux启动过程 本文详细分析了Linux桌面操作系统的启动过程,涉及到BIOS系统.LILO 和GRUB引导装载程序,以及bootsect.setup.vmlinux等映像文件 ...
- 【Good Bye 2017 C】 New Year and Curling
[链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 枚举前i-1个圆. 哪些圆和它相交. 取圆心纵坐标最大的那个圆就可以了. [代码] #include <bits/stdc++ ...
- 洛谷 P3817 小A的糖果
P3817 小A的糖果 题目描述 小A有N个糖果盒,第i个盒中有a[i]颗糖果. 小A每次可以从其中一盒糖果中吃掉一颗,他想知道,要让任意两个相邻的盒子中加起来都只有x颗或以下的糖果,至少得吃掉几颗糖 ...
- 关于hadoop hdfs里文件为啥上一级大小是0,进去又有大小问题解释?
问题 好像跟平时的理解不一样,外边是0,进去就是有大小了? 答:hdfs具体文件是针对具体文件的,不是文件目录. 文件夹大小为0,不是里面所有内容为0.
- 利用jquery.fullPage.js 和 scrolloverflow.min.js 实现滚屏效果
参考链接:https://blog.csdn.net/c11073138/article/details/79631036 /* 按着思路去search. */
- vue 自定义分页组件
vue2.5自定义分页组件,可设置每页显示条数,带跳转框直接跳转到相应页面 Pagination.vue 效果如下图: all: small(只显示数字和上一页和下一页): html <temp ...
- Maven搭建Spring Security3.2项目详解
本来是打算在上一篇SpringMVC+Hibernate上写的,结果发现上面那篇 一起整合的,结果发现上一篇内容实在是太长了,就另起一篇,这篇主要是采用 Maven搭建Spring+SpringMVC ...
