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