Spring: Using @Qualifier with Property Placeholder

后端 未结 3 2037
温柔的废话
温柔的废话 2020-12-19 02:23

I am trying to use a property placeholder as the attribute for @Qualifier, as follows:

@Autowired
@Qualifier(\"${beanName}\")
private MyBean myBean;
<         


        
相关标签:
3条回答
  • 2020-12-19 03:01

    I encountered exactly same issue. Just use Resource

    @Resource(name="${beanName}")
    private MyBean myBean;
    
    0 讨论(0)
  • 2020-12-19 03:06

    Just a try (don't really known the problem to solve) . You can use fixed bean name as usual (autowire with placeholder is not supported) but you can load different bean implementation from different xml based on property value.
    . Else think about a solution based on bean alias. My 2 cents

    0 讨论(0)
  • 2020-12-19 03:17

    I can't leave a comment so this is my answer:

    As Adam B said maybe you can use spring profiles to achieve the result you are aiming to (wich result are you aiming?).

    Another thing you can do is:

    configure a map (using the spring util namespace) in your xml context configuration like this:

     <util:map id="mapId" key-type="java.lang.String" value-type="com.xxx.interface-or-superclass">
            <beans:entry key="${property.bean.name.1}" value-ref="bean1-defined-elsewehere"/>
            <beans:entry key="${property.bean.name.2}" value-ref="bean2-defined-elsewehere"/>
            <beans:entry key="${property.bean.name.3}" value-ref="bean3-defined-elsewehere"/>
      </util:map> 
    

    then you can load this map in a bean called eg. "com.xxx.BeanSelector"

    @Value("#{mapId}")
    private Map<String, com.xxx.interface-or-superclass> myMap;
    

    and add to this bean a methos like this:

    public interface-or-superclass getBean(String beanName){
        return myMap.get(beanName);
    }
    

    ok now you can have your final class similar to this:

    @Autowired
    private BeanSelector beanSelector;
    
    @Value("${property.name.the.bean.you.want.to.use}")
    private String beanName;
    
    private interface-or-superclass myBean;
    

    then you can istantiate myBean (maybe inside the method afterPropertiesSet() if you are implementing the interface InitializingBean)

    in this way:

    myBean = beanSelector.getBean(beanName);
    // then check ifthe bean is not null or something like that
    

    Ok it's a little messy and maybe you can act in a different way based on what you want achieve, but it's a workaround.

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