首页 > 编程语言 > 详细

获取Spring容器Bean对象工具类

时间:2018-06-20 19:36:04      阅读:188      评论:0      收藏:0      [点我收藏+]
        在开发中,总是能碰到用注解注入不了Spring容器里面bean对象的问题。为了解决这个问题,我们需要一个工具类来直接获取Spring容器中的bean。因此就写了这个工具类,在此记录一下,方便后续查阅。废话不多说,直接上代码。

一、代码

  1. package com.zxy.demo.spring;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationContextAware;
  5. import org.springframework.stereotype.Component;
  6. /**
  7. * 获取Spring容器中bean工具类
  8. * @author ZENG.XIAO.YAN
  9. * @date 2018年6月6日
  10. *
  11. */
  12. @Component("springContextUtils")
  13. public class SpringContextUtils implements ApplicationContextAware {
  14. private static ApplicationContext applicationContext = null;
  15. public static ApplicationContext getApplicationContext() {
  16. return applicationContext;
  17. }
  18. @SuppressWarnings("unchecked")
  19. public static <T> T getBean(String beanId) {
  20. return (T) applicationContext.getBean(beanId);
  21. }
  22. public static <T> T getBean(Class<T> requiredType) {
  23. return (T) applicationContext.getBean(requiredType);
  24. }
  25. /**
  26. * Spring容器启动后,会把 applicationContext 给自动注入进来,然后我们把 applicationContext 赋值到静态变量中,方便后续拿到容器对象
  27. * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
  28. */
  29. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  30. SpringContextUtils.applicationContext = applicationContext;
  31. }
  32. }

二、用法

        直接在代码用调用SpringContextUtils静态方法获取bean就ok,可以通过bean的id获取,也可以通过bean的类型获取
  1. RedisUtil redisUtil = SpringContextUtils.getBean(RedisUtil.class);

三、注意事项

        仔细看代码可以发现我这个工具类上面加了个@Component注解。加这个注解的目的是为了把的SpringContextUtils的实例化交给Spring容器管理。当然,你也可以在xml中配置这个,我为了方便,直接用的注解。注意点:这个工具类的实例化必须由Spring容器来做

获取Spring容器Bean对象工具类

原文:https://www.cnblogs.com/zeng1994/p/cf6f754e69da87a46f449aee93dca9d9.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!