@Autowired 与@Resource

Author: wuxinliulei
Link: https://www.zhihu.com/question/39356740/answer/80926247
Source: Zhihu The
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

@Autowired and @Resource:
1. Both @Autowired and @Resource can be used to assemble beans. Both can be written on fields or setter methods.

2. @Autowired is assembled by (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
@Autowired() @Qualifier("baseDao")    
private BaseDao baseDao;
3. @Resource is an annotation supported by JDK1.6. It is assembled according to the name by default . 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 taken by default, and the name is searched. If The annotation is written on the setter method by default with the property name for 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.
<noscript><img src="https://pic3.zhimg.com/50/1d434624eb4918db0814529bbcfbc6b7_hd.jpg" data-rawwidth="201" data-rawheight="392" class="content_image" width="201"> ;</noscript>
It's just that the annotation processor we use is provided by Spring, which is the same. There is no such thing as decoupling or decoupling. The two are equivalent in terms of convenience.

Java code
@Resource(name="baseDao")    
private BaseDao baseDao; 
The main difference between them is that @Autowired is by default assembled by type @Resource by default is assembled
by name and automatically assembled by parameter name. If the name of a bean is the same as the property of another bean, it will be automatically assembled.
byType is automatically assembled by the data type of the parameter. If the data type of a bean is compatible with the data type of the property attribute of another bean, it will be automatically assembled
------------------- -------------------------------------------------- -------------------------------------------------- ------------------
We can use the automatic injection function in the Bean class through @Autowired or @Resource, but the Bean is still defined in the XML file through <bean> -- That is to say, define the Bean in the XML configuration file, and provide the function of automatic injection for the Bean's member variables, method parameters or constructor parameters through @Autowired or @Resource.
For example the following beans.xml
package com.wuxinliulei;

public class Boss {
    private Car car;
    private Office office;

    // 省略 get/setter

    @Override
    public String toString() {
        return "car:" + car + "\n" + "office:" + office;
    }
}


<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-2.5.xsd">
 
    <context:annotation-config/> 

    <bean id="boss" class="com.wuxinliulei.Boss"/>
    <bean id="office" class="com.wuxinliulei.Office">
        <property name="officeNo" value="001"/>
    </bean>
    <bean id="car" class="com.wuxinliulei.Car" scope="singleton">
        <property name="brand" value=" 红旗 CA72"/>
        <property name="price" value="2000"/>
    </bean>
</beans>
Three bean objects are defined, but there is no content pointed to by the ref of our book order,
such as
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="boss" class="com.wuxinliulei.Boss">
        <property name="car" ref="car"/>
        <property name="office" ref="office" />
    </bean>
    <bean id="office" class="com.wuxinliulei.Office">
        <property name="officeNo" value="002"/>
    </bean>
    <bean id="car" class="com.wuxinliulei.Car" scope="singleton">
        <property name="brand" value=" 红旗 CA72"/>
        <property name="price" value="2000"/>
    </bean>
</beans>

-------------------------------------------------------------------------------------------------------

Spring 2.5 provides annotation-based configuration, and we can inject dependencies through annotations. In Java code, you can use @Resource or @Autowired annotations for line injection. Although both @Resource and @Autowired can be used to inject dependencies, there is a difference between them. Let's take a look first:

a.@Resource默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来装配注入;
b.@Autowired默认是按照类型装配注入的,如果想按照名称来转配注入,则需要结合@Qualifier一起使用;
c.@Resource注解是由JDK提供,而@Autowired是由Spring提供
 
@Resource的方式;
d. @Resource和@Autowired都可以书写标注在字段或者该字段的setter方法之上

2. Using the annotation method, we need to modify the header information of the spring configuration file and modify some red annotations, as follows

<?xml version="1.0" encoding="UTF-8"?>
<beans http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="Index of /schema/context"
       xsi:schemaLocation="Index of /schema/beans 
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
Index of /schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
               
<context:annotation-config/>
     
</beans>

PS:

----------------------PS start ---------------------------- -----

In the configuration file that configures Spring based on the host method, you may see

<context:annotation-config/>

Such a configuration, his role is to register with the Spring container

AutowiredAnnotationBeanPostProcessor
CommonAnnotationBeanPostProcessor
PersistenceAnnotationBeanPostProcessor
RequiredAnnotationBeanPostProcessor

These 4 BeanPostProcessors.

The purpose of registering these four BeanPostProcessors is for your system to recognize the corresponding annotations.

E.g:

If you want to use the @Autowired annotation, you must declare the AutowiredAnnotationBeanPostProcessor bean in the Spring container in advance. The traditional way of declaration is as follows

<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/> 

If you want to use annotations such as @Resource, @PostConstruct, @PreDestroy, you must declare CommonAnnotationBeanPostProcessor

<bean class="org.springframework.beans.factory.annotation. CommonAnnotationBeanPostProcessor"/> 

If you want to use the @PersistenceContext annotation, you must declare the PersistenceAnnotationBeanPostProcessor bean.

<bean class="org.springframework.beans.factory.annotation.PersistenceAnnotationBeanPostProcessor"/> 

If you want to use the @Required annotation, you must declare the Bean of RequiredAnnotationBeanPostProcessor.

Again, the traditional way of declaring is as follows:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> 


Generally speaking, these annotations are still commonly used, especially the annotations of Antowired , which are often used during automatic injection, so if it is always necessary to configure one by one in the traditional way, it is a bit cumbersome and unnecessary, so spring gives us Provides a simplified configuration method of <context:annotation-config/> to automatically complete the declaration for you.

However, huh, we use annotations to generally configure scan package path options

<context:component-scan base-package=”XX.XX”/>

This configuration item actually includes the function of automatically injecting the above processor, so when using <context:component-scan/>, <context:annotation-config/> can be removed.

for example:

<context:component-scan base-package="carPoolingController, carPoolingService, carPoolingDao" />

Scan all the annotations under the dao package under the service package under the controller package


--------------------------------------------------------End of PS-- ----------------------------

3. After modifying the header information of the above configuration file, we can inject the bean in the Java code through annotation, see the following code

(1)@Resource

public class StudentService3 implements IStudentService {
    //@Resource(name="studentDao")放在此处也是可行的
    private IStudentDao studentDao;

    private String id;


    public void setId(String id) {
    this.id = id;
    }

@Resource(name="studentDao") // This annotation is used to find the bean named studentDao from the spring configuration file to assemble the field studentDao. If there is no bean named studentDao in the spring configuration file, it will turn to search according to the bean type

public void setStudentDao(IStudentDao studentDao) {
        this.studentDao = studentDao;
}
public void saveStudent() {
        studentDao.saveStudent();
        System.out.print(",ID 为:"+id);
}
}
 

Add the following information to the configuration file

<bean id="studentDao" class="com.wch.dao.impl.StudentDao">
</bean>

<bean id="studentService3" class="com.wch.service.impl.StudentService3"></bean>

(2)@Autowired

public class StudentService3 implements IStudentService {
  //@Autowired放在此处也是可行的
  private IStudentDao studentDao;

  private String id;
  
  public void setId(String id) {
       this.id = id;
   }

@Autowired

// Through this annotation, the bean that satisfies the studentDao type is found from the spring configuration file
//@Qualifier("studentDao") is used to find the transferred bean according to the name.
 public void setStudentDao(IStudentDao studentDao) {
       this.studentDao = studentDao;
  }


  public void saveStudent() {
       studentDao.saveStudent();
       System.out.print(",ID 为:"+id);
  }
}
 

Add the following information to the configuration file

<bean id="studentDao" class="com.wch.dao.impl.StudentDao"></bean>
<bean id="studentService3" class="com.wch.service.impl.StudentService3" />

In java code, you can use @Autowire or @Resource annotations for assembly. The difference between these two annotations is:
@Autowire is assembled by type by default. By default, it requires that the dependent object must exist. If it is allowed to be null, you can set its required attribute If it is false, if we want to use assembly by name, it can be used in conjunction with the @Qualifier annotation;


@Resource is assembled by name by default. When no bean matching the name is found, it will be assembled by type. It can be specified by the name attribute. If the name attribute is not specified, when the annotation is marked on the field, the name of the field is used as the bean name by default. Find the dependent object, when the annotation is marked on the property's setter method, that is, by default, the property name is used as the bean name to find the dependent object.

Note: If the name attribute is not specified, and the dependent object is still not found according to the default name, it will fall back to assembly by type, but once the name attribute is specified, it can only be assembled by name.


--------------------------

When we inject objects for class configuration in xml, we will find that xml files will become more and more bloated and troublesome to maintain. At this time, we can use the annotation mechanism to inject objects into the class configuration.

Java provides us with the annotation javax.annotation.Resource.

The spring framework provides org.springframework.beans.factory.annotation.Autowired.

In general, we use the annotation javax.annotation.Resource, because this way we can achieve decoupling with the spring framework (can't agree, because the annotation processor is still provided by Spring).

@Resource can act on fields and functions. When applied to fields, if we simply write

@Resource
PersonDao  p;

At this time, the process of spring injecting p is 1: first check whether there is an element with id p in the xml

2: If it is not found, see if there is a name attribute (@Resource name=""), and if so, find the name

3: Otherwise find an element of type PersonDao

@Resource can be used on set functions.

E.g:

@Resource
public void setP(PersonDao p) {
  this.p = p;
}

The @Autowired annotation is to search according to the type, such as PersonDao p, he will go to the xml file to find the element of type PersonDao

Guess you like

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