首页 > 编程语言 > 详细

springboot 通过类名称获取bean

时间:2020-05-11 16:38:39      阅读:1377      评论:0      收藏:0      [点我收藏+]

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;
    }

}

 

springboot 通过类名称获取bean

原文:https://www.cnblogs.com/panchanggui/p/12869912.html

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