Autowiring spring bean by name using annotation

In the latest version of Springs we can autowire bean use annotation as @Autowired . It will be an autwire bean using its type (or constructor, if applicable on it). Is there a way to use the @Autowired annotation based on the bean name that we did without annotation in the Spring XML file as autowire = "byName" ?

+45
spring autowired
Aug 6 2018-12-12T00:
source share
5 answers

You can use the JSR-250 @Resource for auto-bean if you do not need to inject a constructor or insert a few parameters.

From the docs:

If you intend to express the injection introduced by the annotation by name, do not use @Autowired basically, even if it is technically possible to refer to the bean name via @Qualifier values. Instead, use the JSR-250 @Resource annotation, which is semantically defined to identify a specific target component by its unique name, and the declared type is not relevant to the matching process.

+43
Aug 6 '12 at 15:35
source share

You can use:

 @Autowired @Qualifier("beanname") 

According to @Qualifier javadoc

This annotation can be used in a field or parameter as a qualifier for fan-candidates for automatic training.

+89
Aug 06 '12 at 15:33
source share

I used a bean proxy that messed up autowiring by name. @Resource did not have this problem, since it does not care about type. So now I know one reason for this recommendation by the Spring developers :-) Just FYI

+2
Mar 18 '13 at 14:44
source share

If you want to determine the name of the bean with which they will be registered in the DI container, you can pass the name in the annotation itself, for example. @Service ("employeeManager").

Then, using the code below, you can enable autwire by name

 @Autowired @Qualifier("employeeManager") private EmployeeManagerService employeeManagerService; 
+2
Jul 07 '16 at 7:00
source share

Use @Component ("beanname") in your bean's java class definition

Then, when autoinstallation uses JSR 330

@Inject @Named (Value = "beanname")

+1
Oct. 16 '17 at 8:29 on
source share



All Articles