Spring can't autowire Map bean

前端 未结 3 1731
无人及你
无人及你 2020-11-29 02:03

I\'ve defined a map in spring as such:



        
相关标签:
3条回答
  • 2020-11-29 02:53

    Seems like your @Qualifier(value = "AdditionalParams") is not working.

    Try using the map by following annotation :

    @Resource
    private Properties AdditionalParams;
    

    and keeping your applicationContext.xml file intact.

    0 讨论(0)
  • 2020-11-29 02:57

    Starting with Spring 4.3, @Autowired can inject lists and maps and the given code in the question would work:

    That said, as of 4.3, collection/map and array types can be matched through Spring’s @Autowired type matching algorithm as well, as long as the element type information is preserved in @Bean return type signatures or collection inheritance hierarchies.

    But with a lower Spring version, you can't autowire a collection like that. However, you can do the following:

    @Resource(name="AdditionalParams")
    private Map<String, String> additionalParams;
    

    or even:

    @Value("#{AdditionalParams}")
    private Map<String, String> additionalParams;
    

    Check the spring docs, the tips section:

    beans that are themselves defined as a collection or map type cannot be injected through @Autowired, because type matching is not properly applicable to them. Use @Resource for such beans

    0 讨论(0)
  • 2020-11-29 03:03
    @Autowired ApplicationContext ctx;
    private  <T> T getBean(String qualifier, Class<T> returnType){
        //use this for loop to print all bean from ctx. so you wont miss the typo.
        /*for(String s:ctx.getBeanDefinitionNames())
            log.info(s);*/
        return ctx.getBean(qualifier, returnType);
    }
    

    // inside your call

     if(providerList == null){
           providerList = ctx.getBean("providerList", Map.class);
     }
    

    This Solution works good to me

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