【发布时间】:2019-05-01 15:05:00
【问题描述】:
我有以下课程:
@Configuration
public class ActionsConfig {
private Map<ObjectType, List<Action>> map = new HashMap<>();
@Bean
public Action1 action1() {
return new Action1();
}
@Bean
public Action2 action2(){
return new Action2();
}
@Bean
public Action3 action3(){
return new Action3();
}
private void fillMap(){
//here I am filling my map
}
public Map<ObjectType, List<Action>> getMap(){
return this.map;
}
}
Action1、Action2 和 Action3 类实现了一个通用的Action 接口。
然后,在我的服务中,我自动连接 ActionsConfig 类并获取地图。
@Service
public class BasketService {
@Autowired
private ActionsConfig actionsConfig;
...
public void doSomething(){
...
actionsConfig.getMap()...
...
}
}
有没有办法只自动连接地图,从而直接使用地图中的值?
【问题讨论】:
-
将@Bean 添加到
getMap()方法(尝试想出一个更好的名称),并在需要的地方@Autowire 映射。但是,fillMap()可能会在 一些 的布线已经完成之后被调用,这可能是一个问题,具体取决于地图的使用方式 - 只需确保在使用之前填充它。此外,请注意并发性 - 如果需要,将地图设为 ConcurrentHashMap。 -
@AndrewS 谢谢,我这样做了,我按照下面给出的答案进行操作,但是,我应该自动装配方法,而不是地图本身吗?
-
这取决于你,但请参阅other discussion,它建议使用构造函数注入。
标签: java spring spring-boot autowired