【发布时间】:2020-01-13 21:03:20
【问题描述】:
我了解到,在春季,我可以通过如下配置的名称自动连接/注入Map<String, SomeBeanInterface>:
public interface DummyInterface{
}
@Component("impl1")
public class Impl1 implement DummyInterface{
}
@Component("impl2")
public class Impl2 implement DummyInterface{
}
public class SomeUsage{
@Autowired
private Map<String, DummyInterface> mapping;
// ...
}
并通过字符串检索Component,例如:
SomeUsage use = new SomeUsage();
DummyInterface dummy = use.getMapping().get("impl1");
// do sth...
但是,如果bean映射的key不是String的类型,而是用户定义的Enum的类型,我应该如何将bean注入到enumMap中呢?
我已经阅读了一些帖子并了解到它可以通过 xml 文件进行配置。但似乎xml配置与<Enum, Bean>对紧密耦合,这意味着每次如果我添加一个新的<Enum, Bean>对,我都必须同步配置文件,看起来与我目前的解决方案,即仍然使用<String, Bean> 集合并自己维护java 代码中的<Enum, String> 映射。有没有更好的解决方案来处理这个问题?还是我错过了什么?
【问题讨论】:
-
现在如何注入 bean 来映射?
-
@chaoluo 只需在集合图上添加
@Autowired注释即可。抱歉,我错过了原始帖子中的那一行。
标签: java spring spring-boot dependency-injection autowired