Spring @Autowired and @Resource difference

Spring @Autowired and @Resource Profile

  1. @Autowired @Resource are doing and use injected Bean, but not @Resource Spring annotations, including where she is javax.annotation.Resource, Spring provides the injection of the annotation

Autowired explanation

  1. Autowired byType is automatically injected, Bean find the corresponding class in accordance with the present ApplicationContext injection parameters, to find if a plurality of throws an exception,
  2. Notes Autowired have required, the default is True to not be as null, required = false can be modified as may be null

Resource explain

  1. Resource default is injected in accordance with byName look at ApplicationContext according to the parameter name to be injected, if can not find the will to find and inject bean accordance byType
  2. There annotation Resource name and type attributes, without loading a different configuration
    a. If both the name and type, and the type of the corresponding name to be matched, can not be found an exception is thrown
    b. If the name, according to the name to find, can not find Throws
    c If you specify a type, and then Autowired similar, can not find or to find out more will throw an exception.
    d If both are not implemented, it will follow byName, byType order to find.;

Simple to understand:

Spring source complex, bloggers detailed flow not locate individuals generally understood as follows:

  1. First read Bean spring-config.xml spring configured and loaded into ApplicationContext
  2. Injection subject or set by the constructor method xml configuration
  3. The configuration or context xml: component-scan to scan and annotations Autowired Resource class, need to find a configuration of Bean to the ApplicationContext, assigned to the last object properties directly reflected by the way, the injection is completed.

to sum up:

  1. Under ordinary circumstances develop, and there is no difference between the two, which contains most of the functionality Resource of Autowired
  2. When injected class is null, Autowired (required = false) is more appropriate
  3. When a need to create a different class of object is instantiated Spring, when introduced Resource (name = "* service") is more appropriate

Guess you like

Origin blog.csdn.net/zhangyong01245/article/details/93621164