spring injection annotation

The difference between @Autowired, @Inject, and @Resource of annotation

 

一、@Autowired

1. @Autowired is an annotation that comes with spring, and dependency injection is implemented through the 'AutowiredAnnotationBeanPostProcessor' class;

2. @Autowired is automatically assembled according to type . If you need to assemble by name, you need to cooperate with @Qualifier;

3. @Autowired has an attribute of required, which can be configured to false. If it is configured to false, when the corresponding bean is not found, the system will not throw an error;

4. @Autowired can act on variables, setter methods, and constructors.

 

a. Write @autowored on the injected member variable, so there is no need to configure it in the xml file, and remove the corresponding setter and getter methods in the program,

 

b. It can also be written on the constructor and setter methods

 

c、@Qualify

The XX in @Qualifier("XXX") is the name of the bean, so when @Autowired is used in combination with @Qualifier, the auto-injection strategy is changed from byType to byName.

However, it should be noted that @Autowired can annotate member variables, methods, and constructors, while @Qualifier's annotation objects are member variables, method parameters , and constructor parameters .

 

2. @Inject

1. @Inject is a specification in JSR330 (Dependency Injection for Java), which needs to import javax.inject.Inject; implement injection.

2. @Inject is automatically assembled according to the type . If you need to assemble by name, you need to cooperate with @Named;

3. @Inject can act on variables, setter methods, and constructors.

 

a. Apply @Inject to variables, setter methods, and constructors, just like @Autowired

 

b、@Named

The XX in @Named ( "XXX") is the name of the bean, so when @Inject and @Named are used in combination, the automatic injection strategy is changed from byType to byName .

 

 

3. @Resource

1. @Resource is the implementation of the JSR250 specification and needs to import javax.annotation to achieve injection.

2. @Resource is automatically assembled according to the name , and a name attribute is generally specified.

3. @Resource can act on variables and setter methods.

 

a. @Resource instance

 

 

 

Summarize:

1. @Autowired comes with spring, @Inject is implemented by JSR330 specification, @Resource is implemented by JSR250 specification, and different packages need to be imported

2. The usage of @Autowired and @Inject is basically the same, the difference is that @Autowired has a request attribute

3. @Autowired and @Inject are matched by type by default, and @Resource is matched by name

4. If @Autowired needs to be used with @Qualifier according to the name matching, @Inject is used with @Name

Guess you like

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