静态方法获取spring的bean实例
文章目录
- 1 场景
- 2 思路
- 3 代码
- 3.1 定义bean
- 3.2 注册bean
- 3.3 使用
- 4 扩展
- 4.1 源码讲解
- 4.2 注意事项
1 场景
spring命名空间中的bean,正常情况下可以使用@Autoware
注解加在成员变量上注入,注入成功的前提是注入的对象必须已经是spring命名空间中的bean才可以。
当前有一种需求:通过工具类的静态方法,获取spring中的bean
。
2 思路
(1)定义bean
(2)bean实现ApplicationContextAware
接口
3 代码
3.1 定义bean
/*** spring上下文句柄*/
public class SpringContextHolder implements ApplicationContextAware {/*** spring上下文*/private static ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringContextHolder.applicationContext=applicationContext;}/*** 获取spring上下文* @return*/public static ApplicationContext getApplicationContext(){return applicationContext;}/*** 获取bean* @param name bean名称* @param <T>* @return*/public static <T> T getBean(String name){if(applicationContext==null){return null;}return (T) applicationContext.getBean(name);}/*** 获取bean* @param requiredType bean类型* @param <T>* @return*/public static <T> T getBean(Class<T> requiredType){if(applicationContext==null){return null;}return applicationContext.getBean(requiredType);}/*** 获取bean* @param name bean名称* @param requiredType bean类型* @param <T>* @return*/public static <T> T getBean(String name, Class<T> requiredType){if(applicationContext==null){return null;}return applicationContext.getBean(name,requiredType);}
}
3.2 注册bean
spring配置文件中,加载的xml最前面
定义上述bean:
<!-- spring上下文句柄 -->
<bean id="springContextHolder" class="com.sa.demo.spring.context.SpringContextHolder"/>
3.3 使用
在java代码的任何一个地方执行下面代码,可以获取spring中的bean:
SpringContextHolder.getBean("xxxxxx");
SpringContextHolder.getBean("XXX.class")
SpringContextHolder.getBean("xxxxxx","XXX.class")
获取spring中的命名空间:
ApplicationContext applicationContext=SpringContextHolder.getApplicationContext();
4 扩展
4.1 源码讲解
加载原理:
实现的接口ApplicationContextAware
中的方法定义如下:
/*** Set the ApplicationContext that this object runs in.* Normally this call will be used to initialize the object.* <p>Invoked after population of normal bean properties but before an init callback such* as {@link org.springframework.beans.factory.InitializingBean#afterPropertiesSet()}* or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and* {@link MessageSourceAware}, if applicable.* @param applicationContext the ApplicationContext object to be used by this object* @throws ApplicationContextException in case of context initialization errors* @throws BeansException if thrown by application context methods* @see org.springframework.beans.factory.BeanInitializationException*/
void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
翻译如下:
设置运行该对象的ApplicationContext。
通常这个调用将用于初始化对象。
在填充普通bean属性之后,在init回调之前调用
表示实现此接口的bean,将在填充bean属性之后,bean的init回调方法之前,调用此方法。方法的参数
为spring的命名空间ApplicationContext
bean实现此接口后,会被调用相应方法,取决于以下源码:
方法路径:
org.springframework.context.support.ApplicationContextAwareProcessor#postProcessBeforeInitializationorg.springframework.context.support.ApplicationContextAwareProcessor#invokeAwareInterfaces
对应方法如下:
private void invokeAwareInterfaces(Object bean) {if (bean instanceof EnvironmentAware) {((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());}if (bean instanceof EmbeddedValueResolverAware) {((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);}if (bean instanceof ResourceLoaderAware) {((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);}if (bean instanceof ApplicationEventPublisherAware) {((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);}if (bean instanceof MessageSourceAware) {((MessageSourceAware) bean).setMessageSource(this.applicationContext);}if (bean instanceof ApplicationContextAware) {((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);}
}
相应扩展部分:
当spring中注册的bean实现了如下接口:
EnvironmentAware
EmbeddedValueResolverAware
ResourceLoaderAware
ApplicationEventPublisherAware
MessageSourceAware
ApplicationContextAware
均会执行上述代码中对应的实现方法。
4.2 注意事项
(1)此类bean的定义,需在spring最前面定义。
(2)实现了接口ApplicationContextAware
的bean,只能获取此bean所定义的spring命名空间。
静态方法获取spring的bean实例相关推荐
- java spring获取bean_普通Java类获取Spring的Bean的方法
普通Java类获取Spring的Bean的方法 在SSH集成的前提下.某些情况我们需要在Action以外的类中来获得Spring所管理的Service对象. 之前我在网上找了好几好久都没有找到合适的方 ...
- Java普通类获取Spring框架Bean 的五种方法
方法一:在初始化时保存ApplicationContext对象 代码: ApplicationContext ac = new FileSystemXmlApplicationContex(" ...
- Spring内部bean实例
在Spring框架中,一个bean仅用于一个特定的属性,这是提醒其声明为一个内部bean.内部bean支持setter注入"property"和构造器注入"constru ...
- 普通Java类获取Spring的bean
在SSH集成的前提下.某些情况我们需要在Action以外的类中来获得Spring所管理的Service对象. 之前我在网上找了好几好久都没有找到合适的方法.例如: ApplicationContext ...
- Spring IOC 容器源码分析 - 获取单例 bean
1. 简介 为了写 Spring IOC 容器源码分析系列的文章,我特地写了一篇 Spring IOC 容器的导读文章.在导读一文中,我介绍了 Spring 的一些特性以及阅读 Spring 源码的一 ...
- 获取Spring容器管理的Bean工具类
很多时候我们在一些不受spring管理的类中需要用到spring管理的Bean,那么这个时候可以使用如下工具类从spring容器中获取相关的Bean实例. @Component public clas ...
- 天天用 Spring,bean 实例化原理你懂吗?
来源:小小木的博客 www.cnblogs.com/wyc1994666/p/10650480.html 本次主要想写spring bean的实例化相关的内容.创建spring bean 实例是spr ...
- factorybean 代理类不能按照类型注入_彻底搞懂依赖注入(一)Bean实例创建过程
点击上方"Java知音",选择"置顶公众号" 技术文章第一时间送达! 上一章介绍了Bean的加载过程(IOC初始化过程),加载完成后,紧接着就要用到它的依赖注入 ...
- 在ServletContextListener实现类中获取spring注入对象
由于项目需要,需在ServletContextListener监听接口实现类中调用spring注入的对象,以获取系统初始化参数.代码如下: [java] view plain copy import ...
最新文章
- 【java】兴唐第二十节课(Collection 和 ArrayList)
- 让浏览器非阻塞加载javascript的几种方式
- Java 设计模式之工厂模式
- 深度探讨验证码发展史,账户中心安全科普文
- 部署Dotnet Core应用到Kubernetes(二)
- 【转】17.Qt界面布局管理详解
- php三级栏目调用,织梦当前栏目调用二级、三级栏目且栏目高亮解决方法
- Vue如何循环提取对象数组中的值
- python OOP(2)
- oracle hint firstrow,Dynamics AX 2009客户端配置文件启动路径问题
- MFC 线程创建方式
- deepin 惠普打印驱动安装
- asp.net开源资料——国内.NET论坛源代码
- QQ微信实现连续发送消息【代码实现】
- 使用OpenCV编写图像窗宽窗位动态调节程序
- 创蓝云智短信接口发送短信函数
- 温暖的奢侈,当手机遇到机器人
- 【转】DotNetNuke常用扩展模块
- Unity3d实现Projector(喷码效果)
- 下载微软虚拟学院视频字幕,解决本地播放没有字幕
热门文章
- Linux网络协议栈:中断下半部处理
- 为什么你的发行版仍然在使用“过时的”Linux 内核? | Linux 中国
- 中科大计算机学院推免生录取名单,中科大2016年推免生拟录取名单
- Python生态概览(一):数据分析库、数据可视化库、文本处理库、机器学习库、深度学习库
- Python程序控制结构(二)循环结构:for in遍历循环,while无限循环,循环+else
- fiddler修改支付金额_支付漏洞总结
- sklearn学习总结
- 利用ECG关于HRV分析
- 翻转单词顺序列C语言,剑指offer刷题之c、c++实现的翻转单词顺序列
- linux 关闭redis 命令_面试必问的 Redis:RDB、AOF、混合持久化