Affects: Spring Boot 2.5.1
@Lookup
(org.springframework.beans.factory.annotation.Lookup
) method fails to find bean by a given name.
Example: * I have multiple singleton beans implementing an interface * I have added a lookup method with argument(for bean name) * when I invoke the lookup method it fails with error "NoUniqueBeanDefinitionException: No qualifying bean of type 'com.example.pattern.factory.api.Pizza' available: expected single matching bean but found 4: cheesePizza,clamPizza,pepperoniPizza,veggiePizza]"
public abstract class Pizza {}
@Service
@Qualifier("cheesePizza")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class CheesePizza extends Pizza {}
@Service
@Qualifier("clamPizza")
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ClamPizza extends Pizza {}
Lookup method
@Lookup
protected Pizza getPizza(String name){
return null;
};
public Pizza startPreparing(String name){
Pizza pizza = getPizza(name);
return pizza;
}
Comment From: sbrannen
Thanks for getting in touch, but it feels like this is a question that would be better suited to Stack Overflow. As mentioned in the guidelines for contributing, we prefer to use the issue tracker only for bugs and enhancements. Feel free to update this issue with a link to the re-posted question (so that other people can find it) or add some more details if you feel this is a genuine bug.
Comment From: sagarvilas
As you say sir, I am sure it is a bug. According to documentation https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/beans/factory/annotation/Lookup.html "The resolution of the target bean can either be based on the return type (getBean(Class)) or on a suggested bean name (getBean(String))", but resolution by bean name is not happening.
Comment From: ttddyy
Hi @sagarvilas ,
The javadoc of @Lookup#value
says:
This annotation attribute may suggest a target bean name to look up. If not specified, the target bean will be resolved based on the annotated method's return type declaration.
The code that handles @Lookup
passes value
attribute as its beanname.
Then, the actual logic that performs a bean lookup by name does so when beanname is available.
So, I think you need to put @Lookup("cheesePizza")
or @Lookup("clamPizza")
if there are multiple beans defined with the type, unless I am reading the code wrong.
Comment From: sagarvilas
@ttddyy Thank you, you are correct, I was reading the documentation wrong. But I think it might be a good idea to have a dynamic lookup so that the bean can be resolve at run-time.