Autowiring spring bean by name using annotation

SpringAutowired

Spring Problem Overview


In Springs latest version, we can autowire a bean using annotation as @Autowired. This will autowire the bean using its type(or constructor, if applied on it). Is there any way I can use the @Autowired annotation based on the bean name which we were doing without annotation in Spring's XML file as autowire="byName"?

Spring Solutions


Solution 1 - Spring

You can use:

@Autowired
@Qualifier("beanname")

According to the @Qualifier javadoc

> This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring

Solution 2 - Spring

You can use JSR-250 @Resource for by-name bean autowiring, unless you need constructor injection or multi-parameter method injection.

From the docs:

> If you intend to express annotation-driven injection by name, do not primarily use @Autowired, even if is technically capable of referring to a bean name through @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, with the declared type being irrelevant for the matching process.

Solution 3 - Spring

If you want to define name of the bean with which they will be registered in DI container, you can pass the name in annotation itself e.g. @Service (“employeeManager”).

Then using below code you can enable autowire by Name

@Autowired
@Qualifier("employeeManager")
private EmployeeManagerService employeeManagerService;

Solution 4 - Spring

I was using bean name proxy which was messing up autowiring by name. @Resource didn't have that issue since it doesn't care about type. So now I know one reason for this recommendation by Spring developers :-) Just FYI

Solution 5 - Spring

Use @Component("beanname") in the java class definition of your bean

Then while autowiring use JSR 330

@Inject @Named(Value="beanname")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnandView Question on Stackoverflow
Solution 1 - SpringBiju KunjummenView Answer on Stackoverflow
Solution 2 - SpringsoulcheckView Answer on Stackoverflow
Solution 3 - SpringtinkuView Answer on Stackoverflow
Solution 4 - SpringjeetView Answer on Stackoverflow
Solution 5 - SpringNandanView Answer on Stackoverflow