2

I am interested to inject a bean reference, which is resolved based on another property on the same bean:

@Autowired
@Qualifier("#{'prefix' + actualQualifier}")
private OtherBean otherBean

private String actualQualifier;

This would ensure that the relationship between "actualQualifier" and "otherBean" is correct.

There is a number of beans configured of the type OtherBean.

I can make sure that "actualQualifier" has a value set before autowiring/injection begins.

I am unable to find any way to reference another property value (in the JavaBean sense) on the same bean that is currently being autowired.

Dennis Thrysøe
  • 1,791
  • 4
  • 19
  • 31

1 Answers1

2

AFAIK, this will not work. SpEL has no access to variables of the enclosing class. And anyway, it looks like @Qualifier does not process SpEL expressions.

I did some tests and never found how to use a SpEL expression as a @Qualifier value. This page from Spring forums (and the error messages from Spring) let me think that in fact @Qualifier only takes a String and does not try to evaluate a SpEL expression.

My conclusion is that way will lead you in a dead end.

As suggested in this other answer, I think you'd better use a selector bean and set otherBean in an init method :

@Bean(initMethod="init")
class MyBean {
...
    @Autowired
    private BeanSelector beanSelector;
    private OtherBean otherBean
    private String actualQualifier;

    public void init() {
        otherBean = beanSelector(actualQualifier);
    }
...
}

and put all intelligence about the choice of otherBean in beanSelector.

Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • That just moved the problem. Then I would need N x qualifierName beans, and no need to know which to use. The main point is that there is N different bean "pairs" that need to find each other somehow. – Dennis Thrysøe Apr 21 '15 at 13:14
  • @DennisThrysøe : it is even worse than that :-( . But see my edit for another way to get it done. – Serge Ballesta Apr 21 '15 at 15:16