use*_*476 5 java autowired spring-boot
假设我有一个“ SomeInterface”和两个实现该“ SomeInterface”的springComponentImpl。
我知道我可以使用以下方法一次将两个实现自动连线:
@Autowire
private List<SomeInterface> springComponentsImplList;
Run Code Online (Sandbox Code Playgroud)
我可以用这种方式注入它们吗:
@Autowire
private Map<String,SomeInterface> springComponentsImplList;
Run Code Online (Sandbox Code Playgroud)
这样我就可以通过“键”来实现?如果该键是类名或类似的东西并且是自动生成的,那将是完美的。
谢谢!
以下内容应该是开箱即用的,其中映射包含 bean 名称作为键,相应的 bean 实例作为值:
@Autowired
private Map<String, Foo> allBeansOfType;
Run Code Online (Sandbox Code Playgroud)
但您也可以尝试使用以下命令获取特定类型的所有 bean 实例及其名称ListableBeanFactory:
private Map<String, Foo> allBeansOfType;
@Autowired
public MyClass(ListableBeanFactory beanFactory) {
this.allBeansOfType = beanFactory.getBeansOfType(Foo.class);
}
Run Code Online (Sandbox Code Playgroud)