Spring implements access to Bean objects more simply (using annotations to store and inject Bean objects)

Table of contents

I. Introduction: 

Second, store the Bean object

5 categories of annotations

@Bean method annotation

3. Get the Bean object

attribute injection

Advantages and disadvantages 

Setter injection

Advantages and disadvantages analysis 

constructor injection

 Advantages and disadvantages analysis

Classic interview questions: What is the difference between property injection, constructor injection and Setter injection?

The Difference Between @Resource VS @Autowired


I. Introduction: 

In the last blog, we talked about the general process of a spring core project:

Create a project - "store the object in the Spring container -" take out the Bean object from the Spring container

But, the processes mentioned in the previous article are still too cumbersome. Is there an easier way to achieve object access?

Of course there is, let's take a look!

First of all, the creation of the Spring project - there is nothing to say about this! Just follow the steps in our previous blog.

But note: Compared with the previous blog, the configuration file of spring has changed - in order to realize the storage of Bean objects more easily (store the object in spring)

The changed spring configuration file

<?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:content="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <content:component-scan base-package="在对象储存中,要扫描的路径"></content:component-scan>
</beans>

Second, store the Bean object

First of all, let's recall that we implement the way of storing Bean objects.

When we stored beans before, we needed to add a line of bean registration content in spring-config, as shown in the following figure:

This way of depositing Bean is not very good!
1. You need to manually add bean objects to the configuration file
. 2. If there is a problem in the configuration file, it is not easy to debug.

And now we don't need to add the Bean objects we want to store in the spring configuration file one by one. We directly:

 Do you think it is enough to add the scan path to the configuration file?

No, you still need to add annotations to the class - during the re-scanning process, only the annotated classes can be successfully stored in spring

This leads us to the notion of annotations

There are two methods:
1. Use 5 categories of annotations to implement

1. @Controller [Controller - controller]
2. @Service [service - service]
3. @Repository [repository - warehouse]
4. @Configuration [configuration - configuration/layout]
5. @Component [component - component]

through the above Any one of the five categories of annotations can store beans in Spring.

2. By method annotation @Bean, a bean can also be stored in Spring.

5 categories of annotations

We used the @Service annotation above, and the other four annotations @Controller and @Repository are the same.

Supplement 1: 

Since the usage of these five categories of annotations is so similar, why are they divided into five different annotations? Is it not good to unify into one annotation?

To answer this question, we must first understand the knowledge of software engineering

 

The reason why I talk about the definition of "software layering" is to pave the way for the later explanation of "why there are five annotation categories"!

let's see

Since these five categories of annotations correspond to different layers in the software layering—they have different functions to be implemented.

It is not difficult to understand why it is divided into five categories for annotations,

Supplement 2:

You may still have a question: why? Our Spring must have the following configuration?

What does it mean if there is no such configuration? ?

You can imagine:
In a Spring project, our classes can be divided into two types:

1. Classes that require inversion of control, and classes whose "life cycle" is handed over to Spring to manage. [For example: UserController]

2. There is no need to store classes in Spring.


Suppose we have a large-scale project, and the classes that need to be stored in Spring and the classes that do not need to be stored in Spring account for a 50-50 split.
This will cause problems!
If we don't describe this line of code in the root directory,
Spring will scan all the classes to see which of these classes are there.


but! The classes that need to be stored in Spring in the project only account for 50%.
That is: Spring will waste twice the time to check for classes that do not need to be stored in Spring.
Therefore, in order to improve the efficiency of Spring, you must specify the directory to scan for me.
Make sure that in this directory, there must be classes that need to be stored in Spring.

In this way, Spring only needs to scan the classes in the corresponding directory, and that's it!
 


@Bean method annotation

Above, we have implemented the simple storage of Bean objects in spring through the five major types of annotations and the Bean method. So how to simply get the Bean object from spring?


3. Get the Bean object

Obtaining bean objects is also called object assembly, which is to take out objects and put them into a certain class, sometimes called object injection.

Object injection is actually DI in our spring - dependency injection.

IoC and DI are the two most important concepts in Spring, among which IoC (Inversion of Control) is the idea of ​​inversion of control, and DI (Dependency Injection) is its (IoC) specific implementation. So how many ways does DI implement dependency injection? How are these injection methods different?

There are three common ways to implement dependency injection through @Autowired in Spring:

  1. Field Injection;
  2. Setter Injection;
  3. Constructor Injection.


attribute injection

Therefore, it can be concluded that:

When using @Autowired for property injection
, if the injected object is stored in Spring multiple times, then no matching bean can be found just by the type of the property! It is necessary to change the variable name of the attribute to BeanName, find the matching object (bean) according to the BeanName and perform attribute injection.

There are more than one method, but the method of "accurately describing the name of the bean" mentioned above is the simplest and most efficient!

Isn't it very simple, you don't need to get Spring's context object and getBean method, you can get the corresponding bean directly through an annotation (take out the bean from Spring).
 

Let's look at another example

When there are multiple beans of the same type, non-unique bean exceptions may occur.

 

So how do we solve this problem?

Two ways:

1. Change your attribute name to the method name student1 or student2 in the class

 

2. Use @Qualifier to filter beans 

Advantages and disadvantages 

advantage:

The biggest advantage of attribute injection is that it is simple to implement and easy to use . You only need to add an annotation (@Autowired) to the variable, and you can directly obtain the injected object without new objects (this is the function and charm of DI. )

 

shortcoming:

  1. Functional issues: unable to inject an immutable object (final modified object - cannot be initialized);
  2. Universality problem: only suitable for IoC container;
  3. Design principle problem: It is easier to violate the single design principle (because of the convenience of use, property injection may be used extensively in the program).

Setter injection

Advantages and disadvantages analysis 

As can be seen from the above code, Setter injection is much more troublesome than property injection .

advantage:

If there are any advantages of Setter injection, the first thing to bear the brunt is that it fully complies with the design principle of single responsibility, because each Setter only targets one object .

shortcoming:

But its shortcomings are also obvious, and its shortcomings are mainly reflected in the following two points:

  1. Immutable objects cannot be injected (finally modified objects - cannot be initialized through the constructor);
  2. The injected object can be modified (the setter method can be called multiple times)

constructor injection

 Advantages and disadvantages analysis

advantage:

Compared with the previous two injection methods, constructor injection can inject immutable objects, and it will only be executed once, and there is no such thing as Setter injection where the injected object is modified at any time. Its advantages are as follows: indivual:

  1. Injectable immutable objects (initialized in the constructor);
  2. The injected object will not be modified (in a class, the constructor can only be called once);
  3. The injected object will be fully initialized;
  4. It is more versatile (that is, it can be used for both IoC containers and non-IoC containers).

shortcoming:

Because multiple parameters can be passed in the construction method, it is easy to violate the principle of singleness



Classic interview questions: What is the difference between property injection, constructor injection and Setter injection?


The Difference Between @Resource VS @Autowired

@Autowired is the annotation provided by spring, @Resource is the annotation provided by jdk

1. Different usage

  • @Autowired, supports property injection, constructor injection, and Setter method injection.
  • @Resource: Support property injection and Setter method injection. Constructor injection is not supported.

2. The attribute injection of @Resource is more comfortable to use than the attribute injection of @Autowired. Because @Resource has many properties that can be set; while @Autowired has only one value property.

There are many attributes, which means that many other functions can be used.
For example, when there are multiple beans of the same type above, there may be exceptions of non-unique beans. If it is @Autowired, we also need an additional @Qualifier to filter and merge beans.

And @Resource can directly:

Guess you like

Origin blog.csdn.net/weixin_61061381/article/details/127823096