ApplicationContextAware接口的作用

我会带着你远行 2022-03-08 15:42 357阅读 0赞

转载: https://blog.csdn.net/bailinbbc/article/details/76446594

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

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

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

public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;

  1. /\*\*
  2. \* 获取静态变量中的ApplicationContext.
  3. \*/
  4. public static ApplicationContext getApplicationContext() \{
  5. assertContextInjected();
  6. return applicationContext;
  7. \}
  8. /\*\*
  9. \* 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
  10. \*/
  11. @SuppressWarnings("unchecked")
  12. public static <T> T getBean(String name) \{
  13. assertContextInjected();
  14. return (T) applicationContext.getBean(name);
  15. \}
  16. /\*\*
  17. \* 从静态变量applicationContext中得到Bean, 自动转型为所赋值对象的类型.
  18. \*/
  19. public static <T> T getBean(Class<T> requiredType) \{
  20. assertContextInjected();
  21. return applicationContext.getBean(requiredType);
  22. \}
  23. /\*\*
  24. \* 清除SpringContextHolder中的ApplicationContextNull.
  25. \*/
  26. public static void clearHolder() \{
  27. applicationContext = null;
  28. \}
  29. /\*\*
  30. \* 实现ApplicationContextAware接口, 注入Context到静态变量中.
  31. \*/
  32. @Override
  33. public void setApplicationContext(ApplicationContext applicationContext) \{
  34. SpringContextHolder.applicationContext = applicationContext;
  35. \}
  36. /\*\*
  37. \* 检查ApplicationContext不为空.
  38. \*/
  39. private static void assertContextInjected() \{
  40. Validate.validState(applicationContext != null,
  41. "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
  42. \}

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

例如:

在CacheUtil中通过spring容器创建CacheManager实例

public class CacheUtils {
private static CacheManager cacheManager = ((CacheManager) SpringContextHolder.getBean(“cacheManager”));
}

发表评论

表情:
评论列表 (有 0 条评论,357人围观)

还没有评论,来说两句吧...

相关阅读