0

I have the following 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;
  }
}

The classes Action1, Action2 and Action3 implements a common Action interface. Than, inside my service, I autowire the ActionsConfig class and get the map.

@Service
public class BasketService {
     @Autowired
     private ActionsConfig actionsConfig;
     ...
     public void doSomething(){
        ...
        actionsConfig.getMap()...
        ...
     }
}

Is there a way to autowire just the map, and hence to use the values inside the map directly?

sammy333
  • 1,384
  • 6
  • 21
  • 39
  • Add @Bean to the `getMap()` method (try to come up with a better name), and @Autowire the map where needed. However, `fillMap()` might be called after _some_ of the wiring is already complete which might be a problem depending on how the map is used - just make sure it's populated before using it. Also, be careful with concurrency - make the map a ConcurrentHashMap if needed. – Andrew S Nov 29 '18 at 14:36
  • @AndrewS Thanks, I did so and I followed the answer given bellow, but then, should I autowire the method, not the map itself? – sammy333 Nov 30 '18 at 09:34
  • It's up to you, but see this [other discussion](https://stackoverflow.com/questions/21218868/explain-why-constructor-inject-is-better-than-other-options) which recommends using constructor injection. – Andrew S Nov 30 '18 at 14:59

1 Answers1

1

You can create a method that's annotated with @Bean.

  @Bean
  public Map<ObjectType, List<Action>> getMap() {

    Map<ObjectType, List<Action>> map = new HashMap<>();
    fillMap()

    return map;
  }

You can then use @Autowired to autowire the map.

@Autowired
private Map<ObjectType, List<Action>> myMap;
Jerome
  • 81
  • 1
  • 6
  • Thank you for your answer. Just a question - I guess I should Autowire the name of the method right? (i.e. `@Autowired private Map> getMap;`). not `myMap`? – sammy333 Nov 30 '18 at 09:31
  • Nope. The variable name does not have to be the same as the method name. The Spring container will inject a bean of type Map>. – Jerome Nov 30 '18 at 11:09