我如何只用 spring-boot 注入一个 Map<Object, List<Object>>?
How do I inject just a Map<Object, List<Object>> with spring-boot?
我有以下 class:
@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;
}
}
classes Action1
、Action2
和 Action3
实现了通用的 Action
接口。
然后,在我的服务中,我自动连接 ActionsConfig
class 并获取地图。
@Service
public class BasketService {
@Autowired
private ActionsConfig actionsConfig;
...
public void doSomething(){
...
actionsConfig.getMap()...
...
}
}
有没有办法只自动装配地图,从而直接使用地图中的值?
您可以创建一个用@Bean 注释的方法。
@Bean
public Map<ObjectType, List<Action>> getMap() {
Map<ObjectType, List<Action>> map = new HashMap<>();
fillMap()
return map;
}
然后您可以使用@Autowired 来自动装配地图。
@Autowired
private Map<ObjectType, List<Action>> myMap;
我有以下 class:
@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;
}
}
classes Action1
、Action2
和 Action3
实现了通用的 Action
接口。
然后,在我的服务中,我自动连接 ActionsConfig
class 并获取地图。
@Service
public class BasketService {
@Autowired
private ActionsConfig actionsConfig;
...
public void doSomething(){
...
actionsConfig.getMap()...
...
}
}
有没有办法只自动装配地图,从而直接使用地图中的值?
您可以创建一个用@Bean 注释的方法。
@Bean
public Map<ObjectType, List<Action>> getMap() {
Map<ObjectType, List<Action>> map = new HashMap<>();
fillMap()
return map;
}
然后您可以使用@Autowired 来自动装配地图。
@Autowired
private Map<ObjectType, List<Action>> myMap;