1 Spring not only supports its own definition of @Autowired annotations, but also supports several annotations defined by the JSR-250 specification, which are @Resource, @PostConstruct, and @PreDestroy.
2 the effect of @Resource is equivalent to @Autowired, but according to the @Autowired byType automatic injection, @Resource injection..@Resource byName automatically by default has two attributes is more important, is name and type, Spring name analysis of @Resource attributes for the bean annotation name, and the type property for the bean type. So the analysis if you use the name attribute, automatic injection strategy using byName, and use the type attribute with the byType automatic injection strategy. If neither a name nor type property is specified, then through the reflection mechanism using byName
automatic injection strategy.
3 @Resource assembly sequence
1. if the name and type are specified at the same time, the unique matching bean is found from the Spring context, and the exception
is thrown if it is not found
2., if name is specified, the bean that matches the name (ID) is assembled from the context, and if it is not found, the exception
3. if you specify type, you can find the unique bean of type matching from the context, assemble, fail to find or find multiple, and throw the exception
4. if the name is not specified and type is not specified, the assembly is performed automatically according to the byName method; if no match is made, the rollback is matched to an original type; if matched, the assembly is automatically performed;
The difference between 4 @Autowired and @Resource:
1, both @Autowired and @Resource can be used to assemble bean.. They can either be written on fields or written on the setter method.
2, the default @Autowired according to the type of assembly (this note is spring by default), must rely on object must exist, if you want to allow null values, can set its required property to false, such as: @Autowired (required=false), if we want to make the name of the assembly can be combined with the @Qualifier annotation using
3, @Resource (this note belongs to J2EE), the name of the default installation assembly name can be specified by the name attribute, if you do not specify the name attribute, when write a note on the field, the field name default installation name lookup, if the annotation write attribute name assembly default in the setter method when looking for. Not with the name matching bean only according to the type of assembly. But note that if the name property once specified, will assemble.
5 recommends using the @Resource annotation on the field so that you don't have to write the setter method, and this annotation belongs to J2EE and reduces the coupling to the spring, so that the code looks more elegant than.