Why is it recommended that you use @Resource over @Autowired?

Click on the “Java base” above, select “Set as star”

Be a positive person, not a positive waste person!

Update articles every day at 14:00, lose a million bits of hair every day…

Source code boutique column

  • Original | Java 2021 Super God Road, very liver~

  • An open source project with detailed annotations in Chinese

  • RPC framework Dubbo source code analysis

  • Network application framework Netty source code analysis

  • Message middleware RocketMQ source code analysis

  • Database middleware Sharding-JDBC and MyCAT source code analysis

  • Job Scheduling Middleware Elastic-Job Source Code Analysis

  • Distributed transaction middleware TCC-Transaction source code analysis

  • Eureka and Hystrix source code analysis

  • Java Concurrency Source Code

Source: blog.csdn.net/weixin_43715214/

article/details/127858049

  • What’s the difference between @Autowired and @Resource?

  • Same point

  • difference

  • Why is @Resource more recommended?

f29deae4fa1184928d7e49d557889f4d.png

What is the difference between @Autowired and @Resource?

Both @Autowired and @Resource annotations are used for bean injection!

Among them, @Autowired is the annotation provided by Spring; @Resource is not provided by Spring, but by JDK, but Spring supports the injection of this annotation, which is not required when using it Import out-of-shelf packages.

Background management system + user applet based on Spring Boot + MyBatis Plus + Vue & amp; Element, supports RBAC dynamic permissions, multi-tenancy, data permissions, workflow, three-party login, payment, SMS, mall and other functions

  • Project address: https://github.com/YunaiV/ruoyi-vue-pro

  • Video tutorial: https://doc.iocoder.cn/video/

The same point

Both can be written on properties or setter methods.

If both are written on the field, then there is no need to write the setter method anymore!

Background management system + user applet based on Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & amp; Element, supporting RBAC dynamic permissions, multi-tenancy, data permissions, workflow, three-party login, payment, SMS, mall and other functions

  • Project address: https://github.com/YunaiV/yudao-cloud

  • Video tutorial: https://doc.iocoder.cn/video/

The difference

@Autowired

By default, it is injected according to byType!

we can give an example

public class TestServiceImpl() {
 
    @Autowired
    private UserDao userDao;
 
    ...
}

The above code will first go to the container to find out which objects are of type UserDao, and assign specific values to userDao after finding them (but if more than one is found, an error will be reported!)

The @Autowired annotation assembles dependent objects according to type (byType). By default, it requires that dependent objects must exist; if null values are allowed, we can set the required attribute to false.

If we want to assemble by name, we can use it in conjunction with the @Qualifier annotation

Q: If our UserDao has multiple implementation classes, such as UserDaoImpl1, UserDaoImpl2, how should we write our code?

If you don’t use @Qualifier, then byType is used by default, and multiple UserDao types will be found, and an error will be reported! ! ! So write it like the code below! ! !

Option 1 (@Qualifier)

public class TestServiceImpl() {
 
    @Autowired
    @Qualifier("userDaoImpl1") // specify which implementation class
    private UserDao userDao;
 
    ...
}

Option Two (@Primary)

In @Autowired, if there are multiple beans, but we don’t want to use @Qualifier, we can do this:

Use the @Primary annotation to specify one for injection! ! !

@Primary
@Mapper
public class UserDaoImpl01 implements UserDao {
    ...
}
@Mapper
public class UserDaoImpl02 implements UserDao {
    ...
}

@Resource

The default is to inject byName, and if the name cannot be found, it will be injected by type.

There are two important attributes name and type in @Resource

In Spring, the name attribute of the @Resource annotation is parsed into the name of the bean, and the type is the type of the bean.

  • If the name attribute is used, the automatic injection strategy of byName is used

  • If the type attribute is used, the automatic injection strategy of byType is used

  • If not specified, this will use the byName automatic injection strategy through the reflection mechanism

Assembly order of @Resource

1) If both name and type are specified, the only matching bean is found from the Spring context for assembly, and an exception is thrown if it cannot be found

2) If name is specified, look for a bean with a matching name (id) from the context for assembly, and throw an exception if it cannot be found

3) If type is specified, the only bean that matches the type is found from the context for assembly. If no or multiple beans are found, an exception will be thrown

4) If neither name nor type is specified, it will be automatically assembled according to the byName method. If there is no match, it will fall back to a primitive type (UserDao) for matching, and if it matches, it will be automatically assembled. (Name first, then type)

Why is it recommended to use @Resource?

The Resource annotation is on the field. This annotation belongs to J2EE, which reduces the coupling with spring.

But in fact, I think many people may have misunderstood this question!

It is more recommended to use @Resource , I don’t think it is because the @Resource annotation has better performance or something.

It is because it can specify whether to inject by name or type, and the @Autowired annotation itself cannot achieve this effect, it must be used together with @Qualifier !

Welcome to join my knowledge planet, discuss architecture and exchange source code together. How to join, Long press the QR code below:

3b9ea38cd037eec1d22237ddfa458994.png

The source code has been updated on Knowledge Planet and the analysis is as follows:

138dce8632b6d88c593ea8785ee78dfc.jpeg

f58d557b486e101d9b1b5be0a38262bd.jpeg

88a125fda94577c53ff9bb340c769ef7.jpeg

087b4028d94f17137815af14dce108e0.jpeg

The recently updated series “Introduction to Taro SpringBoot 2.X” has more than 101 articles, covering MyBatis, Redis, MongoDB, ES, sub-database and sub-table, read-write separation, SpringMVC, Webflux, permissions, WebSocket, Dubbo, RabbitMQ, RocketMQ , Kafka, performance testing, etc.

Provides a SpringBoot example with nearly 3W lines of code, and an e-commerce microservice project with more than 6W lines of code.

How to get it: Click “Looking“, follow the official account and reply to 666 to receive, more content will be provided one after another.

If the article is helpful, please read it and forward it.
Thank you for your support (*^__^*)