Everyone knows that these two annotations can achieve bean injection
@Autowired This is spring's annotation org.springframework.beans.factory.annotation.Autowired
@Resource This belongs to the annotation javax.annotation.Resource that comes with java
@Autowired is injected by type by default, and dependent objects must exist by default.
- If you allow the dependent object to be null, you need to set the required attribute to false,
If you need to inject by name, you can use it with @Qualifier
@Resource is injected according to the name attribute inside
- If name is not specified
- When the annotation is on the field, name=field name assembly is taken by default.
- When the annotation is on the setter method, name=property name assembly is taken by default.
- When assembling by name (by-name) does not match, assembling by type (by-type).
- When the specified name attribute is displayed, it can only be assembled by name (by-name).
@Resoure assembly sequence
- If the name and type attributes are specified at the same time, the only matching bean assembly will be found, and an exception will be thrown if it is not found;
- If the name attribute is specified, it will be assembled according to the name (by-name), and an exception will be thrown if it is not found;
- If the type attribute is specified, it will be assembled according to the type (by-type), and an exception will be thrown if it is not found or if more than one is found;
- If neither the name attribute nor the type attribute is specified, it will be assembled according to the name (by-name); if it is not found, it will be assembled according to the type (by-type).
Compare
Comparison item | @Autowire | @Resource |
---|---|---|
Annotation source | Spring annotation | JDK annotations (JSR-250 standard annotations, belonging to J2EE) |
Assembly method | Priority by type | Priority by name |
Attributes | required | name、type |
Scope of action | Fields, setter methods, constructors | Field, setter method |
@Resource is recommended
- Annotations belong to J2EE, reduce coupling with Spring