Spring and @Autowired compare notes @Resource

Look at the source code comments

/**Autowired
 * Marks a constructor, field, setter method or config method as to be
 * autowired by Spring's dependency injection facilities.
 */
/**Resource 
 * The Resource annotation marks a resource that is needed
 * by the application.  This annotation may be applied to an
 * application component class, or to fields or methods of the
 * component class.  */

1. Same:

Can be marked Fields, Method,

They are used to inject bean

2. Different

Autowired:

1) provided by a spring, you need Import  org.springframework.beans.factory.annotation.Autowired

2) based on matching the type of injection bean

3) having the required properties, the default required = true, so there must be one and only one type of the bean object. If required = false, then the object can be null bean type

4) If you want to use the name to assemble, may be combined with the use @Qualifier annotation. Such as: @Qualifier ( "xxx")


Resource :

1) provided by the java, need import javax.annotation.Resource

2) based on the default bean name matches injection

3) has a name, type important attributes, using the following method:

If you specify the name and type attributes at the same time, so there must be one and only one of that name, the type of bean object , or throws an exception.

If only the name (@Resource (name = "xxx ")) property, you must have an id = "xxx" the bean, or throw an exception.

If you only specify the type attribute, so this must be one and only one type of bean object , or throws an exception.

If the name, type attributes are not specified, in accordance with the spring looks bean name = field value; if not found, press type to find; if not found, throw an exception

4) Another authenticationType, shareable, mappedName, description attributes, with less, not explained in detail here.



Published 33 original articles · won praise 2 · views 40000 +

Guess you like

Origin blog.csdn.net/zjj2006/article/details/53117016