Mikhail Valiev
Mikhail Valiev

Reputation: 113

Writing optional bean dependency injection by bean name

I've read some articles on optional bean dependencies, it is usually suggested to use java Optional class, or spring ObjectProvider class.

Those do work, but my case is a little different. What if in my context there are multiple beans of the same type, which annotated with @Qualifier and I don't know if there is a bean I need among them. And I need the one with the specific name.

@ComponentScan(basePackages = "my.package")
public class MyClass {

 private final MyOptionalBean myOptionalBean;

 MyClass(ObjectProvider<MyOptionalBean> myOptionalBeanObjectProvider) {
     this.myOptionalBean = myOptionalBeanObjectProvider.getIfAvailable(() -> null);
 }

}

The example above works. But now imagine, that there are multiple MyOptionalBean beans registered in my context, those beans are named. How do I write the similar code as above, but tell spring to look by the name of specific instance?

Upvotes: 0

Views: 797

Answers (1)

Michael
Michael

Reputation: 44090

You can use @Autowired(required = false) and @Qualifier in combination:

MyClass(@Autowired(required = false) @Qualifier("foo") MyOptionalBean myBean)
{
    // myBean will be null if no bean with the qualifier exists
}

Upvotes: 2

Related Questions