在Web应用中,Spring容器通常采用声明式方式配置产生:开发者只要在web.xml中配置一个Listener,该Listener将会负责初始化Spring容器,MVC框架可以直接调用Spring容器中的Bean,无需访问Spring容器本身。在这种情况下,容器中的Bean处于容器管理下,无需主动访问容器,只需接受容器的依赖注入即可。

但在某些特殊的情况下,Bean需要实现某个功能,但该功能必须借助于Spring容器才能实现,此时就必须让该Bean先获取Spring容器,然后借助于Spring容器实现该功能。为了让Bean获取它所在的Spring容器,可以让该Bean实现ApplicationContextAware接口。

下面示例为实现ApplicationContextAware的工具类,可以通过其它类引用它以操作spring容器及其中的Bean实例。

原文:https://blog.csdn.net/bailinbbc/article/details/76446594


@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext = null; /**
* 获取静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
} /**
* 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
} /**
* 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
} /**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
applicationContext = null;
} /**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
} /**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
Validate.validState(applicationContext != null,
"applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
} }

Spring容器会检测容器中的所有Bean,如果发现某个Bean实现了ApplicationContextAware接口,Spring容器会在创建该Bean之后,自动调用该Bean的setApplicationContextAware()方法,调用该方法时,会将容器本身作为参数传给该方法——该方法中的实现部分将Spring传入的参数(容器本身)赋给该类对象的applicationContext实例变量,因此接下来可以通过该applicationContext实例变量来访问容器本身。
eg: 在CacheUtil中通过spring容器创建CacheManager实例

public class CacheUtils {
private static CacheManager cacheManager = ((CacheManager) SpringContextHolder.getBean("cacheManager"));
  // SpringContextHolder.getBean(CacheManager.calss);
}

ApplicationContextAware 快速获取bean的更多相关文章

  1. 【ApplicationContext】通过实现ApplicationContextAware接口获取bean

    SpringApplicationUtils.java import org.springframework.beans.BeansException; import org.springframew ...

  2. Spring获取bean工具类,可用于在线程里面获取bean

    Spring获取bean工具类,可用于在线程里面获取bean import java.util.Locale; import org.springframework.beans.BeansExcept ...

  3. 从Spring容器中获取Bean。ApplicationContextAware

    引言:我们从几个方面有逻辑的讲述如何从Spring容器中获取Bean.(新手勿喷) 1.我们的目的是什么? 2.方法是什么(可变的细节)? 3.方法的原理是什么(不变的本质)? 1.我们的目的是什么? ...

  4. ApplicationContextAware获取bean

    ApplicationContextAware获取bean 概述 在某些特殊的情况下,Bean需要实现某个功能,但该功能必须借助于Spring容器才能实现,此时就必须让该Bean先获取Spring容器 ...

  5. GreenDao 工具类 --- 使用 Json 快速生成 Bean、表及其结构,"炒鸡"快!

    作者:林冠宏 / 指尖下的幽灵 掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8 博客:http://www.cnblogs.com/linguan ...

  6. FastJson序列化Json自定义返回字段,普通类从spring容器中获取bean

    前言: 数据库的字段比如:price:1 ,返回需要price:1元. 这时两种途径修改: ① 比如sql中修改或者是在实体类转json前遍历修改. ②返回json,序列化时候修改.用到的是fastj ...

  7. Spring中使用两种Aware接口自定义获取bean

    在使用spring编程时,常常会遇到想根据bean的名称来获取相应的bean对象,这时候,就可以通过实现BeanFactoryAware来满足需求,代码很简单: @Servicepublic clas ...

  8. application项目获取bean

    对于web项目,编程方式获取bean如下: WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); C ...

  9. Spring获取bean的几种方式

    工作中需要对一个原本加载属性文件的工具类修改成对数据库的操作当然,ado层已经写好,但是需要从Spring中获取bean,然而,工具类并没有交给Spring来管理,所以需要通过方法获取所需要的bean ...

随机推荐

  1. Html5移动端页面自适应布局详解(rem布局)

    在移动设备上进行网页的重构或开发,首先得搞明白的就是移动设备上的viewport,通读网上的各种对于viewport的解释之后 大概viewport可以理解为三种 1.layout viewport  ...

  2. <input>/<textarea>输入框设置默认提示文字(隐藏式)

    html代码如下: <tr>    <td>签   名:</td>    <td><input type="text" nam ...

  3. nodejs 模板引擎

    自制替换模板 template.js var fs = require('fs') var http = require('http') var server = http.createServer( ...

  4. "不能将值 NULL 插入列 'ID',表 列不允许有 Null 值."

    问题: "不能将值 NULL 插入列 'ID',表 列不允许有 Null 值." 原因: 在进行表创建的时候没有将主键自增字段添加标识. 在使用navicat进行表创建的时候一定要 ...

  5. c# 反射获取属性值 TypeUtils

    using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Sy ...

  6. 2018-10-16-weekly

    Algorithm 判断子序列 What 给定字符串 s 和 t ,判断 s 是否为 t 的子序列.如,"ace"是"abcde"的一个子序列,而"a ...

  7. j函数 判断以 什么开头

    1.str.charAt(index) 返回字符串中指定位置的字符. str 是字符串  我们要将获得的数据 转化为字符串 var code = res.statusCode.toString(); ...

  8. matplotlib.pyplot 包

    import matplotlib.pyplot as plt 图片的打开和保存: from PIL import Image img=Image.open('....') img.save('... ...

  9. Centos7网卡绑定的两种方法

    https://blog.51cto.com/youdong/1963416 选择模式4,并且layer选择3+4,交换机要配置LAG 一.传统的bond方式 (1)bond几种主要模式介绍 ü mo ...

  10. VS2017 IDE 说明