问题
How does Spring @Autowire
beans: byName or byType? If one is not possible, is a second trial done using another mode?
回答1:
If annotated with @Autowired
it will inject the bean with the matching type (An exception will be thrown if there are more than one of a type). To specify a name use the @Qualifier
annotation.
回答2:
Springs @Autowire
wires by type. For wiring by name you can also use
@Resource(name = "id")
回答3:
The default mode of the @Autowired
is byType
.
回答4:
Autowired
annotation on variable or setters method is equivalent to xml attribute autowire="byType"
XML attribute autowire
is defaut as no
"no":
The traditional Spring default. No automagical wiring. Bean references
must be defined in the XML file via the <ref/> element (or "ref"
attribute). We recommend this in most cases as it makes documentation
more explicit.
回答5:
These are no, byName, byType, constructor, and autodetect. The default mode is no i.e. by default autowiring is turned off in traditional XML based configuration.
Using @Autowired annotation-
1) @Autowired on properties:
When @Autowired is used on properties, it is equivalent to autowiring by byType in configuration file.
2) @Autowired on property setters:
When @Autowired is used on setters, it is also equivalent to autowiring by byType in configuration file.
3) @Autowired on constructors:
When @Autowired is used on bean’s constructor, it is also equivalent to autowiring by constructor in configuration file.
Use @Qualifier for conflict in dependency resolution
As we learned that if we are using autowiring in byType mode and dependencies are looked for property class types. If no such type is found, an error is thrown. But, what if there are two or more beans for same class type.
In this case spring will not be able to choose correct bean to inject into property, and you will need to help the container using qualifiers.
To resolve a specific bean using qualifier, we need to use @Qualifier annotation along with @Autowired annotation and pass the bean name in annotation parameter.
来源:https://stackoverflow.com/questions/5665220/autowire-default-mode