zoukankan      html  css  js  c++  java
  • springboot 通过类名称获取bean

    IOC容器有beanFactory 和ApplicationContext.通常建议使用后者,因为它包含了前者的功能。Spring的核心是ApplicationContext.它负责管理 beans 的完整生命周期。我们可以从applicationContext里通过bean名称获取安装的bean.进行某种操作。不能直接使用applicationContext.而需要借助applicationContextAware.具体方法如下:

    @Component
    public class ApplicationContextGetBeanHelper implements ApplicationContextAware {
        private static ApplicationContext applicationContext;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    
        public static Object getBean(String className) throws BeansException,IllegalArgumentException {
            if(className==null || className.length()<=0) {
                throw new IllegalArgumentException("className为空");
            }
    
            String beanName = null;
            if(className.length() > 1) {
                beanName = className.substring(0, 1).toLowerCase() + className.substring(1);
            } else {
                beanName = className.toLowerCase();
            }
            return applicationContext != null ? applicationContext.getBean(beanName) : null;
        }
    
    }

    声明一个ApplicationContextHelper组件,名字随意。它实现了ApplicationContextAware接口。并重写setApplicationContext方法。在该组件里可以通过名字获取某个bean.

    使用

    @Slf4j
    @RestController
    @RequestMapping("/getbean")
    public class GetBeanTestController {
    
        @GetMapping("/retryService")
        public String retryService(@RequestParam int num){
    
            RetryService retryService = (RetryService) ApplicationContextGetBeanHelper.getBean("RetryService");
            String ss = retryService.print();
    
            return ss;
        }
    
    }
  • 相关阅读:
    数据结构学习记录_2019.02.26
    数据结构学习记录_2019.02.23
    数据结构学习记录_2019.02.27
    C语言学习记录_2019.02.23
    本博客所有博文密码均为“000000”
    Oracle触发器
    Oracle重载
    Oracle程序包
    Oracle函数
    Oracle存储过程
  • 原文地址:https://www.cnblogs.com/panchanggui/p/12869912.html
Copyright © 2011-2022 走看看