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