How to correct inject map of bean in spring context

前端 未结 2 346
青春惊慌失措
青春惊慌失措 2020-12-20 14:36

I am using component-scan in my spring application. So in spring context I created map:



        
相关标签:
2条回答
  • 2020-12-20 15:06

    If I were you, I would use Java Config to create a Map, since Java is the best way to create a Java object :) :). Your configuration code would look like this:

    @Bean(name = "mapBean")
    public Map<String, MyCustomClassName1> mapBean() {
        Map<String, MyCustomClassName1> map = new HashMap<>();
        //populate the map here - you will need to @Autowire the references if they are not defined in this configuration
        return map;
    }
    

    And then I would inject it into wherever it's needed like so:

    @Resource(name="mapBean")
    private Map<String, MyCustomClassName1> map;
    

    Note the use of @Resource instead of @Autowired or @Inject

    0 讨论(0)
  • 2020-12-20 15:08

    Quote from the documentation:

    An autowired Maps values will consist of all bean instances that match the expected type, and the Maps keys will contain the corresponding bean names.

    I think that just changing @Inject with @Resource will do it.

    0 讨论(0)
提交回复
热议问题