spring autowiring with unique beans: Spring expected single matching bean but found 2

后端 未结 4 1082
滥情空心
滥情空心 2020-11-30 01:06

I am trying to autowire some beans (for dependency injection) using Spring for a webapp. One controller bean contains another bean which in turn holds a hashmap of another

4条回答
  •  遥遥无期
    2020-11-30 01:39

    The issue is because you have a bean of type SuggestionService created through @Component annotation and also through the XML config . As explained by JB Nizet, this will lead to the creation of a bean with name 'suggestionService' created via @Component and another with name 'SuggestionService' created through XML .

    When you refer SuggestionService by @Autowired, in your controller, Spring autowires "by type" by default and find two beans of type 'SuggestionService'

    You could do the following

    1. Remove @Component from your Service and depend on mapping via XML - Easiest

    2. Remove SuggestionService from XML and autowire the dependencies - use util:map to inject the indexSearchers map.

    3. Use @Resource instead of @Autowired to pick the bean by its name .

       @Resource(name="suggestionService")
       private SuggestionService service;
      

    or

        @Resource(name="SuggestionService")
        private SuggestionService service;
    

    both should work.The third is a dirty fix and it's best to resolve the bean conflict through other ways.

提交回复
热议问题