一、背景
在我们实际开发中,通常通过@Autowired和@Resource来进行bean的获取,其中Autowired默认ByType,Resource默认ByName获取,但是我们如果需要动态的获取bean时,就需要直接借助ApplicationContext的getBean方法进行获取
二、实现
在实现中,自定义一个类实现ApplicationContextAware接口
@Service
public class ContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ContextUtil.applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return applicationContext.getBean(clazz);
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(String name, Class<T> clazz) {
return applicationContext.getBean(name, clazz);
}
}
controller层调用
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/context")
public String getContext() {
CheckService checkService = ContextUtil.getBean("checkLocationService", CheckService.class);
return checkService.getName();
}
}
使用单元测试会出现NPE,需要在controller层进行测试