Spring, using annotations to assemble objects (@Resource, @Autowired)



First, introduce the Jar package used for annotations: common-annotations.jar

The following explains why @Resorce is recommended for annotation:
1. Both @Autowired and @Resource can be used to assemble beans. Both can be written on fields, or written in on the setter method.
2. @Autowired is assembled by type by default (this annotation belongs to spring). By default, the dependent object must exist. If you want to allow null values, you can set its required property to false, such as: @Autowired(required= false) , if we want to use name assembly, we can use it in conjunction with the @Qualifier annotation, as follows:
Java code Collection code
@Autowired() @Qualifier("baseDao")    
private BaseDao baseDao;   
3. @Resource (this annotation belongs to J2EE), By default, the assembly is performed according to the name. The name can be specified by the name attribute.
If the name attribute is not specified, when the annotation is written on the field, the field name is used to search by name by default. If the annotation is written on the setter method, the attribute name is used by default. assembly. Assemble by type when no bean matching the name is found. But it should be noted that if the name attribute is specified, it will only be assembled according to the name.
Java code Collection code
@Resource(name="baseDao")    
private BaseDao baseDao;   

I like to use @Resource annotation on fields, and this annotation belongs to J2EE, which reduces the coupling with spring. The most important thing is that the code looks more elegant.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326337665&siteId=291194637