The difference between @Autowired and @Resource in Spring

The @Autowired annotation is provided by Spring . It can be used to mark the constructor, member variables and method parameters. It can complete automatic injection according to the object type. The code is as follows.

public class Service {


    // 构造方法注入
    @Autowired
    public Service(Service service) {
        this.service = service;
    }


    // 成员变量注入
    @Autowired
    private Service service;
 
    // 方法参数注入
    @Autowired
    public void setService(Service service) {
        this.service = service;
 
    }
}

Look at the @Resource annotation again, the code is as follows.

public class Service {
    
    @Resource(name = "service1")
    private Service service1;
    
    @Resource(name = "service2")
    private Service service2;
 


    @Reource
    private Service service3;
 
    @Reource
    private Service service4;


}

It is provided by JDK , follows the JSR-250 specification, and is a new feature added by JDK 1.6 and above. As a Java standard, its role is no different from @Autowired. Unlike @Autowired, which works with all Java frameworks, @Autowired only works with Spring. Readers can simply understand that @Resource can support object type injection as well as object name injection.

What are the specific differences between @Resource and @Autowired ?

It can be analyzed from the following five aspects.

1. The parameters defined inside the annotation are different

@Autowired contains only one required parameter, which defaults to true, indicating that automatic injection is enabled.

public @interface Autowired {


     // 是否开启自动注入,在不开启自动装配时,可设为false


    boolean required() default true;
 
}

@Resource contains 7 parameters, the two most important of which are name and type.

public @interface Resource {
    // Bean的名称
  
    String name() default "";
 
    String lookup() default "";
 
     // Java类,被解析为Bean的类型
    Class<?> type() default java.lang.Object.class;
 
    enum AuthenticationType {
            CONTAINER,
            APPLICATION
    }
 
    // 身份验证类型
   
    AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
 
   // 组件是否可以与其他组件共享


    boolean shareable() default true;
 
    String mappedName() default "";
 
     // 描述
    String description() default "";
}

2. The default value of the assembly method is different

@Autowired defaults to autowiring by type, while @Resource defaults to autowiring by name. The @Resource annotation can customize the selection of the assembly method. If the name is specified, it will be automatically assembled by name. If type is specified, autowire by type.

3. Annotations apply in different scopes

@Autowired can be used on constructors, member variables, method parameters and annotations, while @Resource can be used on classes, member variables and method parameters. The source code is as follows.

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired { ... }


@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {  ... }

4. source is different

@Autowired is an annotation defined by Spring, while @Resource follows the JSR-250 specification and is defined in JDK. So @Autowired can only be used under the Spring framework, while @Resource can be used with other frameworks.

5. Assembly order is different

@Autowired matches with byType by default first, and if multiple beans are found, it will be matched according to the byName method, and if there are more than one bean, an exception will be reported. The assembly sequence is shown in the figure below.

73eefab34e5a6f5a11b0c970fe2d97f9.png

The loading order of @Resource is divided into the following four situations.

1) If name and type are specified at the same time, the Bean that uniquely matches them will be found from the Spring context for assembly, and an exception will be thrown if it cannot be found. The specific process is shown in the figure below.

b938b8ad8a824d202855353e03135ead.png

2) If name is specified, the Bean that matches the name (ID) will be searched for assembly from the context, and an exception will be thrown if it cannot be found. The specific process is shown in the figure below.

3a064fa06f17caa54f706a5ebf50d9e0.png

3) If type is specified, find the only Bean that matches the type from the context and assemble it. If it cannot find or find more than one, an exception will be thrown. The specific process is shown in the figure below.

fb379fc1f525a09e5fa13d57750f2406.png

4) If neither name nor type is specified, it will be automatically assembled byName. If no matching is successful, the matching is still performed according to the type, and the specific process is shown in the figure below.

f2bf42655caa3908f221e903efeef6ad.png

The following table can help you better understand and distinguish @Autowired and @Resource.

587dea33063b3da8e720cf9bb2926a30.png

To sum up, there is not much difference in function between the two, and they are similar in use. However, it is recommended to use @Autowired in daily development for the following 3 reasons.

1st: @Autowired is slightly more powerful. Supports priority injection and can be configured to allow Bean not to exist.

No. 2: If you use the Spring framework, it is better to use its unique annotations.

No. 3: Some people think that @Resource is more general, because it is a specification, and other frameworks will support it. At present, the backend is using Spring, and there is no need to consider other frameworks.

Interview comments: We can directly tell the interviewer the difference between these two annotations, and at the same time explain more differences based on the characteristics of the two annotations, so that we can better reflect our depth of understanding of this aspect of knowledge. The interviewer wants to test the job seeker's understanding of the Spring dependency injection method, as well as the understanding of the difference between the underlying implementation of the @Autowired and @Resource annotations. It will be easier for job seekers to answer this question after they understand the differences in the underlying implementations.


Dear programmer job seekers, I believe you must have a deep understanding of how difficult the road of job interviews is.

Java basics, multithreading, concurrent programming, collection principles, JVM principles... Ah! Don't mention this to me! The interviewer throws these knowledge points at you at once, as well as the magical Java framework. If you don’t understand Spring Family Bucket, Dubbo, Netty, MyBatis, etc., don’t even think about stepping into the door of this industry. That's right, the Java field is in a mess.

Now there is a powerful new book airborne, bringing a cool Java knowledge in this hot summer. This book is called "Java Interview Stereotype Essay: A Guide to High-frequency Interview Questions and Job Search Strategies" , which is simply the savior of Java job seekers.

e98bda2325433af7cb8cf3ae7e49b68f.png

The book includes nearly 200 high-frequency interview questions in all aspects of Java interviews, from Java basics, concurrent programming, collection principles, to JVM principles, I/O and network programming, to design patterns, distributed and microservices, MySQL Database, cache and NoSQL, message middleware... everything you need, it's hard not to master it! Moreover, the book also provides a large number of practical scenarios and interview resume practical skills. Nearly 20 solutions for classic high-frequency actual combat scenarios , from slow server response to spike design, from architecture design to common solutions, all are "sharp swords" that hurt the heart of job seekers. At the same time, there are more than 10 interview resume practical skills , including resume writing and delivery skills, interview salary negotiation skills, job search decision-making skills, etc., to solve your job hunting problems at once!

3f34da9fb6cbfa6ffdcaf55e21760bc6.png

You can read the detailed table of contents in the book:

Swipe up to read

Part 1 Java Core Knowledge Points 1

Chapter 1 Java Basics 2

1.1 Data Type 2

1.1.1 Why design encapsulation class, what is the difference between Integer and int 2

1.1.2 Why "1000==1000" is false and "100==100" is true 3

1.1.3 After new String("hello"), how many objects are created 6

1.1.4 What is the difference between String, StringBuffer and StringBuilder 8

1.2 Object object 9

1.2.1 How to understand the creation process of Java objects 9

1.2.2 What is deep clone and shallow clone 10

1.2.3 What is the difference between strong references, soft references, weak references, and phantom references 12

1.2.4 How much memory does an empty Object take up? 14

1.2.5 Why rewrite the equals() method must rewrite the hashCode() method 15

1.3 Other Features 17

1.3.1 Please compare the difference between Java and JavaScript 17

1.3.2 What are checked and unchecked exceptions 18

1.3.3 What are the functions of the fail-fast mechanism and the fail-safe mechanism 20

1.3.4 How to understand serialization and deserialization 21

1.3.5 What is SPI and what is it used for 22

1.3.6 Will the finally statement block be executed? 24

1.3.7 What is a memory overflow, what is a memory leak 25

Chapter 2 Concurrent Programming and Multithreading 27

2.1 JUC and locks 27

2.1.1 What is AQS 27

2.1.2 How to understand the realization principle of AQS 28

2.1.3 Why does AQS use a doubly linked list 29

2.1.4 What is CAS 31

2.1.5 What is an optimistic lock, what is a pessimistic lock 32

2.1.6 Under what conditions will deadlock occur, and how to avoid deadlock 33

2.1.7 What is the difference between synchronized and Lock 35

2.1.8 What is a reentrant lock and what is its function 37

2.1.9 What is the implementation principle of ReentrantLock 38

2.1.10 How ReentrantLock implements lock fairness and unfairness 39

2.1.11 Talk about your understanding of row locks, gap locks, and adjacent key locks 40

2.1.12 How to understand the dazzling variety of concurrent locks in Java 42

2.1.13 The blocking queue is consumed asynchronously, how to keep the order 51

2.1.14 What is the implementation principle of the array-based blocking queue ArrayBlockingQueue 52

2.2 Multithreading and thread pool 53

2.2.1 What is the difference between Thread and Runnable 53

2.2.2 What is a daemon thread and what are its characteristics 54

2.2.3 What is the difference between BLOCKED and WAITING thread states 55

2.2.4 Why can't the start thread call the run() method directly, and what
are ? 56

2.2.5 Talk about your understanding of the five state flow principles of Java threads 58

2.2.6 Talk about your understanding of thread pool 60

2.2.7 What are the ways to implement thread pool in Java 62

2.2.8 How does the thread pool recycle threads 63

2.2.9 How does the thread pool implement thread reuse 64

2.2.10 How does the thread pool know that the task of a thread has been executed 65

2.2.11 When the number of tasks exceeds the number of core threads in the thread pool, how to prevent tasks from entering the queue 66

2.2.12 What is false sharing and how to avoid false sharing 67

2.2.13 Why should wait and notify be written in the synchronized code block 69

2.2.14 Will wait and sleep trigger the release of locks and CPU resources 70

2.2.15 What is the use of the volatile keyword, and what is its realization principle 71

2.2.16 Talk about your understanding of CompletableFuture 73

2.2.17 Talk about your understanding of the implementation principle of ThreadLocal 75

2.2.18 What is the difference between CountDownLatch and CyclicBarrier 77

2.2.19 Talk about your understanding of Happens-Before 79

2.3 Thread Safety 81

2.3.1 Talk about your understanding of thread safety 81

2.3.2 What are the ways Java guarantees thread safety 82

2.3.3 How to safely interrupt a running thread 83

2.3.4 Is SimpleDateFormat thread-safe? 84

2.3.5 Will ThreadLocal cause memory leaks in concurrent scenarios? 85

Chapter 3 Principles of Sets 89

3.1 ArrayList 89

3.1.1 How ArrayList realizes automatic expansion 89

3.1.2 Talk about the storage performance and characteristics of ArrayList, Vector and LinkedList 91

3.2 HashMap 92

3.2.1 What is the working principle of HashMap under single thread 92

3.2.2 How does HashMap resolve Hash conflicts 97

3.2.3 When to expand HashMap and how to automatically expand it 99

3.2.4 Why HashMap produces an infinite loop 101

3.2.5 What is the difference between HashMap and TreeMap 104

3.2.6 Why the key of ConcurrentHashMap is not allowed to be null 106

3.2.7 Talk about your understanding of the underlying implementation principles of ConcurrentHashMap 108

3.2.8 How does ConcurrentHashMap ensure thread safety 111

Chapter 4 Principles of the JVM 115

4.1 Introduction to JVM 115

4.1.1 How to understand the Java Virtual Machine and how its structure is designed 115

4.1.2 What is the parent delegation mechanism 119

4.2 Memory management 121

4.2.1 How does the JVM judge that an object can be recycled 121

4.2.2 Talk about your understanding of the main GC algorithms in the JVM 123

4.2.3 Why is the JVM generational age 15 times 125

4.2.4 Why does JVM use metaspace to replace permanent generation 126

Chapter 5 I/O and Network Programming 129

5.1 I/O basics 129

5.1.1 Java has several file copy methods, which one is the most efficient 129

5.1.2 What is the difference between I/O and NIO 130

5.1.3 Talk about your understanding of the I/O multiplexing mechanism 131

5.2 Network programming 135

5.2.1 What is a network quadruple 135

5.2.2 Why does TCP design a 3-way handshake 137

5.2.3 What is the difference between Cookie and Session 138

Chapter 6 Design Patterns 140

6.1 The singleton pattern 140

6.1.1 What are the ways to implement the singleton pattern in Java 140

6.1.2 Under what circumstances can a singleton object be destroyed 143

6.1.3 In the DCL singleton writing method, why do two checks mainly 147

6.1.4 Which scenarios are not suitable for using the singleton pattern 150

6.2 Proxy mode 151

6.2.1 What is a proxy and why use a dynamic proxy 151

6.2.2 Why JDK dynamic proxy can only proxy classes with interfaces 153

6.3 Chain of Responsibility Pattern 155

Part 2 Framework source code and principle 159

Chapter 7 Spring Family Bucket 160

7.1 Spring Framework 160

7.1.1 Why use the Spring framework 160

7.1.2 What is the workflow of Spring IoC 162

7.1.3 What is the difference between BeanFactory and FactoryBean in Spring 164

7.1.4 Talk about your understanding of Spring Bean 165

7.1.5 What does the definition of Spring Bean contain 169

7.1.6 What are the scopes of beans in Spring 172

7.1.7 How to describe the life cycle of Spring Bean 174

7.1.8 Is the Bean in Spring thread-safe? 178

7.1.9 Spring has several ways of dependency injection 179

7.1.10 How does Spring solve the circular dependency problem 180

7.1.11 Which design patterns are used in Spring 183

7.1.12 What are the transaction propagation behaviors in Spring 184

7.1.13 What are the causes of Spring transaction failure 185

7.1.14 What are the ways to implement asynchronous calls in Spring 187

7.1.15 Talk about your understanding of Spring AOP principles 190

7.2 Spring MVC framework 193

7.2.1 Talk about your understanding of Spring MVC 193

7.2.2 Briefly describe the core execution process of Spring MVC 194

7.2.3 Talk about your understanding of the nine major components in Spring MVC 197

7.2.4 Difference between @Autowired and @Resource in Spring 202

7.3 Spring Boot framework 207

7.3.1 Why more and more people choose Spring Boot 207

7.3.2 How to understand Spring Boot convention over configuration 210

7.3.3 What is the implementation principle of Spring Boot's automatic assembly mechanism 211

7.3.4 How to understand the Starter in Spring Boot 213

7.4 Spring Cloud Framework 214

7.4.1 Talk about your understanding of Spring Cloud 214

7.4.2 Talk about the principle of Eureka Server data synchronization 215

7.4.3 Briefly describe the workflow of Nacos configuration update 216

Chapter 8 Common Internet Frameworks 218

8.1 Dubbo framework 218

8.1.1 Briefly describe the advantages and disadvantages of Dubbo and Spring Cloud 218

8.1.2 How to deal with Dubbo service request failure 220

8.1.3 How Dubbo dynamically detects service offline 221

8.2 Netty Framework 223

8.2.1 Talk about your understanding of Reactor mode in Netty 223

8.2.2 How Netty implements zero copy 225

8.2.3 Why the default size of the Netty thread pool is twice the number of CPU cores 228

8.2.4 Talk about your understanding of the working principle of Pipeline in Netty 229

8.3 MyBatis framework 231

8.3.1 Talk about your understanding of the MyBatis cache mechanism 231

8.3.2 What is the difference between # and $ in MyBatis 233

8.3.3 How MyBatis paginates 234

Part 3 Distributed and Middleware 237

Chapter 9 Distributed and Microservices 238

9.1 Distributed Communication 238

9.1.1 Talk about your understanding of the RPC framework 238

9.1.2 What is the difference between HTTP and RPC 240

9.2 Microservice Coordinating Components 242

9.2.1 What is the difference between distributed and microservices 242

9.2.2 Talk about your understanding of load balancing 243

9.2.3 Talk about your understanding of ZooKeeper 248

9.2.4 Briefly describe the principle of the Watch mechanism in ZooKeeper 250

9.2.5 How does ZooKeeper implement Leader election 251

9.3 Distributed locks 254

9.3.1 Talk about your understanding and implementation of distributed locks 254

9.3.2 What is idempotence and how to solve the problem of idempotence 255

9.3.3 Talk about your understanding of the consistent Hash algorithm 256

9.3.4 What are the commonly used distributed ID design schemes 260

9.3.5 Implementing distributed locks, which is better, ZooKeeper or Redis 261

9.4 Distributed transactions 263

9.4.1 How to distinguish between transactions and distributed transactions in Spring 263

9.4.2 Talk about the solution of distributed transaction 264

9.4.3 Talk about your understanding of Seata 265

9.4.4 How to solve the suspension problem in TCC 269

9.5 Current limiting and authentication 271

9.5.1 What are the commonly used current limiting algorithms 271

9.5.2 A brief description of the implementation principle of the snowflake algorithm 273

9.5.3 Briefly describe the sliding window algorithm in the Sentinel component 278

9.5.4 Talk about your understanding of OAuth 279

9.6 DevOps and Cloud Native 283

9.6.1 Talk about your understanding of the Swagger workflow 283

9.6.2 What is Cloud Native 286

9.6.3 What is a service mesh 287

9.6.4 Talk about your understanding of IaaS, PaaS, SaaS 290

Chapter 10 The MySQL Database 293

10.1 Storage Engine 293

10.1.1 Should VARCHAR or CHAR be used to store MD5 values ​​293

10.1.2 Can MySQL VARCHAR be used to store a novel 294

10.1.3 What are the causes of index failure 296

10.1.4 What are clustered and non-clustered indexes 297

10.1.5 Talk about your understanding of B-tree and B+-tree 298

10.1.6 Why the index structure of MySQL adopts B+ tree 302

10.1.7 What are the advantages and disadvantages of MySQL indexes 303

10.1.8 Why the SQL statement hits the index faster than the index does not hit 304

10.1.9 What is the difference between MyISAM and InnoDB engines in MySQL 306

10.1.10 MySQL table design time column use datetime or timstamp 309

10.2 Transactions 310

10.2.1 How to understand the transaction isolation level of MySQL 310

10.2.2 The realization principle of MySQL transaction 312

10.2.3 Talk about your understanding of MVCC 314

10.2.4 How does MySQL's InnoDB solve phantom reading 315

10.3 Performance Optimization 318

10.3.1 Executing SQL response is slow, what troubleshooting ideas do you have 318

10.3.2 What is the use of database connection pool and what are its key parameters 321

10.3.3 Why multi-table relational queries are not recommended in distributed systems 322

Chapter 11 Caching and NoSQL 324

11.1 Redis cache 324

11.1.1 Talk about your understanding of Redis 324

11.1.2 How to solve cache avalanche, cache penetration and cache breakdown 325

11.1.3 Briefly describe the implementation principle of Redis persistence mechanism RDB and AOF 328

11.1.4 Briefly describe the process of AOF rewriting in Redis 330

11.1.5 What is the memory elimination algorithm and principle of Redis 331

11.1.6 Talk about your understanding of the time wheel 333

11.1.7 Is Redis single-threaded or multi-threaded? 334

11.1.8 Does Redis have thread safety issues? 336

11.1.9 How Redis and MySQL ensure data consistency 337

11.2 Other NoSQL 340

11.2.1 Talk about your understanding of NoSQL 340

11.2.2 Compared with FastDFS, the advantages and disadvantages of MinIO are explained 342

11.2.3 Talk about your understanding of Elasticsearch 344

Chapter 12 Messaging Middleware 347

12.1 RabbitMQ 347

12.1.1 Talk about your understanding of MQ (message queue) 347

12.1.2 Talk about your understanding of the working principle of RabbitMQ 350

12.1.3 How RabbitMQ implements message routing 351

12.1.4 How does RabbitMQ ensure that online MQ messages are not lost 353

12.1.5 How RabbitMQ achieves high availability 356

12.2 Kafka 358

12.2.1 Why Kafka is so fast 358

12.2.2 Talk about your understanding of Kafka's zero-copy principle 360

12.2.3 How does Kafka ensure that messages are not lost 362

12.2.4 How Kafka avoids repeated consumption 364

12.2.5 How Kafka guarantees message order consumption 366

12.2.6 Talk about your understanding of the principle of Kafka data storage 368

12.2.7 What is ISR and why should ISR be introduced 370

12.2.8 How does the Kafka copy complete the Leader election 371

12.3 Other middleware 373

12.3.1 Why does RocketMQ give up ZooKeeper 373

12.3.2 Talk about your understanding of the RocketMQ distributed transaction principle 375

12.3.3 Talk about your understanding of Pulsar 377

Part 4 Classic Scenarios and Job Search Strategies 383

Chapter 13 Classic Internet Scenarios 384

13.1 Slow server response 384

13.1.1 Online server CPU soars, how to locate Java code 384

13.1.2 The server in the production environment is slow, how to diagnose and deal with it 386

13.1.3 The load of the online interface has increased sharply, and it is almost unbearable. What is your preferred solution? 388

13.2 Lightning Design 388

13.2.1 How to design a seckill system from a global perspective 388

13.2.2 How to solve the problems of oversell and undersell in seckill system 391

13.2.3 How to design the coupon grabbing business in a million-concurrency scenario 392

13.2.4 How to design a random algorithm for grabbing red envelopes during the Spring Festival 394

13.2.5 How to design the automatic cancellation function of order overtime 396

13.3 Architecture Design 397

13.3.1 How Java Web development solves cross-domain problems 397

13.3.2 How to avoid repeated order submission and payment 401

13.3.3 How to design the database architecture for a monitoring system with a daily data volume of over 3 million pieces 403

13.3.4 How is mobile phone scan code login realized 405

13.3.5 The amount of data in a single online table reaches 100 million, how to do table migration 406

13.3.6 How to count the online status of billion-level users 408

13.3.7 Online MySQL database connection pool leaks, how to troubleshoot 410

13.3.8 What should I do if the SMS verification code interface is frantically swiped 413

13.3.9 Briefly describe the evolution process of the Internet architecture in the past 20 years 414

Chapter 14 Job Interview Strategies 420

14.1 Resume writing and delivery skills 420

14.1.1 Finding a job and starting with a good resume 420

14.1.2 How to deliver resumes effectively and accurately 431

14.1.3 The relationship between resume delivery and career development 433

14.1.4 When is the most effective time to submit a resume 434

14.2 Interview Salary Negotiation Skills 437

14.2.1 Understand the unspoken rules of industry interviews 437

14.2.2 Victory is more likely to be fought with preparation 440

14.2.3 How to better present yourself during the interview process 444

14.2.4 Clever answers to common questions in interviews 448

14.2.5 Capture the interviewer's micro-expressions and respond in time 450

14.2.6 When HR asks salary, what should be said 452

14.3 Job-seeking decision-making skills 455

14.3.1 How to choose when you get multiple offers 455

14.3.2 Whether to go to an outsourcing company 458

14.3.3 How to say goodbye to the current company amicably 460

Appendix A Internet Programmer Career Growth and Development Roadmap 463

Appendix B Ability Model Diagram of Each Growth Stage of Internet Programmer Career 464

Appendix C Java Internet Programmer Technical Growth Path 465

I believe this book can be a powerful booster in your career, get twice the result with half the effort, and easily get your favorite Java job. Don't hesitate, I have already applied for the best price for all the fans, so excited, and finally wish everyone can get their favorite Offer!

Give a book! First come first served!

This time, 5 copies will be given away as fan benefits 

Book donation rules: no lottery, use community points to redeem directly!

Exchange address: http://spring4all.com/3249.html

Come and participate in the construction of community content, learn and grow together!

Click to read the original text to see more community benefits!

Guess you like

Origin blog.csdn.net/j3T9Z7H/article/details/131427488