SpringBoot使用getBeansOfType方法不能获取到所有的实现类

1,001 阅读1分钟

1.现象:

通过 applicationContext.getBeansOfType(CommonSignService.class) 只能获取到一个实现类

Snipaste_2022-10-25_10-15-10.png

已知 CommonSignService 有三个子类

Snipaste_2022-10-25_10-16-54.png

2. 原因

内部代码有循环依赖,导致初始化时bean还未加载

3.解决方法:

a 通过 String[] beanNamesForType = applicationContext.getBeanNamesForType(CommonSignService.class);

先获取bean的 name , 在根据beanName 获取bean


String[] beanNamesForType = applicationContext.getBeanNamesForType(CommonSignService.class);

Arrays.asList(beanNamesForType).forEach(beanName -> {
	CommonSignService signService = (CommonSignService) applicationContext.getBean(beanName);
	strategyMap.put(signService.getSignType(), signService);
});


b. 解决循环依赖的问题

@Lazy 注解

@Autowired
@Lazy
private MergeSignService mergeSignService;

Snipaste_2022-10-25_10-25-05.png