Spring (five categories of annotations, three injection methods of objects and their advantages and disadvantages)

Directory

1. Store Bean objects

1.1 Pre-work: configure the scan path

1.2 Add annotations to store Bean objects

1.2.1 @Controller [Controller storage]

1.2.2 @Service (service storage)

1.2.3 @Repository (warehouse storage)

1.2.4 @Component (component storage)

1.2.5 @Configuration (configuration storage)

1.3 The scope and connection of the five annotations

1.3.1 Why do we need five class annotations?

1.3.2 Naming rules for the five categories of annotations

1.4 Method annotation @Bean

1.4.1 Usage of @Bean

1.4.2 Renaming Beans

2. Get the object

2.1 Attribute injection

2.1.1 Advantage Analysis

2.1.2 Shortcoming Analysis

2.2 Setter method injection

2.2.1 Advantage Analysis

2.2.2 Shortcoming Analysis

2.3 Constructor injection

2.3.1 Advantage Analysis

Note: interview questions

3. @Resource: another injection keyword

3.1 The difference between @Autowired and @Resource

4. Multiple @Bean errors of the same type


After the previous study, we can already realize the basic operation of Spring reading and storing objects, but in the process of operation we
It is found that reading and storing objects is not as “simple” as imagined, so next we have to learn more simple operations of Bean objects
?Law.

Do you want to store and read the core of objects more easily in Spring? Use? Annotations, that is, we will learn about the relevant methods in Spring next.
Focus on solutions to store and read Bean objects.

1. Store Bean objects

When storing beans, you need to add a line of bean registration content in spring-config. The bad thing about this XML file is debugging, and if the XML file reports an error, it will not affect the operation of the project. Even if it reports an error, it may not be found.

1.1 Pre-work: Configure scan path

<?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="com.bit.service"></content:component-scan>
</beans>

To inject the class under that path into the spring package

Tell spring that the classes in the lower directory may be managed by spring

But even if the annotation is added, if it is not a class object under the configured scanning package, it cannot be stored in Spring

1.2 Add annotation storage Bean object

To store objects in Spring, there are two types of annotations available:

1.
Class annotations: @Controller, @Service, @Repository, @Component, @Configuration.

2.
? Method annotation: @Bean

1.2.1 @Controller [Controller Storage]

We configured a scanning path com.demo.component in xml. There is a class called ArticleController in the component. We added an annotation to it called Controller. The meaning of this Controller is to tell spring, because when spring loads, it will Scan this path and all packages below the path to check whether the five types of annotations have been added. When the inspection finds that the object has been added, the object will be stored in the spring, and you can fetch it.

But we can know that we will give the Bean an id before, but there is nothing else in the annotation

By default, when we use spring annotations to store an object in spring, its id is the first letter of the class in lowercase

1.2.2 @Service (service storage)

1.2.3 @Repository (warehouse storage)

1.2.4 @Component (Component Storage)

1.2.5 @Configuration (configuration storage)

1.3 The scope and connection of the five categories of annotations

1.3.1 Why do you need five class annotations?

@Controller (controller): It belongs to the business logic layer and is used to control the user’s behavior. It is used to check the legitimacy/validity of the user. If the parameter is invalid, it means that it is an illegal access, so it cannot continue to go down. After the user comes in, the first one to visit is the controller. After the controller is verified, there is no problem before continuing to go down.

@Service (service): It belongs to the service department and is used to call the persistent class to realize the corresponding function. [It is not directly interacting with the database, it is a control center (that is, doing service arrangement, to determine which function should be called) Which persistence layer code combination realizes the function)].

@Repository (warehouse): It belongs to the persistence layer and directly interacts with the database. Usually, each table corresponds to a warehouse class (@Repository).

@Configuration (configuration); belongs to the configuration layer and is used to configure some information of the current project.

@Component (component): It belongs to the public tool class and provides some public methods.

This is why five annotations are set, because each annotation has its own responsibilities, and the functions corresponding to responsibilities are also different

Among the five annotation classes, Component can be used as the parent class of other annotations

The relationship between other classes can be regarded as brothers

Compare source code:

1.3.2 Naming rules for five types of annotations

We can see that the names in the five categories explained above are all in the form of small humps

So here I have three questions:

Question 1: If the first letter of the class name is lowercase, how to get the Bean from Spring?

Question 2: What if both the first letter and the second letter are capitalized?

Question one:

The acquisition method is the same as the initial letter is capitalized, and the first letter of the class is lowercased to obtain the object

Question Two:

When using the default rule to use the first letter lowercase, it failed, but

The correct way to get the Bean: use the original class name, you can get it successfully

Question 1: If the first letter of the class name is lowercase, how to get the Bean from Spring?

Answer: It is consistent with the capitalization of the first letter, and the first letter of the class name is lowercased to obtain the object.

Question 2: What if both the first letter and the second letter are capitalized?

Answer: When the default rule is used and the first letter is lowercase to get the Bean object, it fails!
The correct way to get the Bean is to use the original class name, and you can get it successfully.

Conclusion: When using the five types of annotations, by default, you only need to lowercase the first letter of the class name to obtain the Bean object; however, when the first letter and the second letter of the Bean object are both capitalized, at this time You need to use the original class name to get the Bean object correctly.

Why is this? Let’s dig deep into the source code:

1.4 Method annotation @Bean

1.4.1 Usage of @Bean

@Bean is added to the method, and only one @Bean can’t store the object in the container, so add an annotation to the class

Bean is to narrow the scope based on class annotation

Note: @Bean annotation cannot be used alone when used, it must be used together with the five major types of annotations, otherwise it is an invalid method annotation

Reason: It is the same as the configuration path in xml. In actual demand, we have a large number of methods. It cannot be said that all methods in all classes should be scanned to see if there are any Bean annotations added. If Bean is added After annotating, store the returned object in spring. If you do this, the performance will be very low. There are far more methods than classes. If you don’t use it with the five major types of annotations, the efficiency will be extremely low.

1.4.2 Renaming Beans

Beans can be renamed by setting the name attribute

@Bean naming rules, when the name attribute is not set, the default name of the bean is the method name,

When the name attribute is set, it can only be obtained through the value corresponding to the renamed name attribute, which means that the bean object cannot be obtained by using the method again.

And it is also possible to have multiple names for a bean, just write multiple names in {} like an array, and that’s it

2. Get object

Obtaining a bean object is also called object assembly, which is to take the object out and put it in a certain class, sometimes called object injection.

Object assembly (object annotation) can be implemented in the following three ways:

1. Attribute note?

2. Structure? Note?

3. Setter note?

2.1 Attribute Injection

Property injection is the most familiar and most used injection method in daily development

Implemented using @Autowired

2.1.1 Advantage Analysis

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

2.1.2 Shortcoming Analysis

1. Functional problem: unable to inject an immutable object (finally modified object);

2. Versatility problem: It can only be adapted to loC containers: if the code of property injection is ported to other non-IoC frameworks, the code will be invalid, so the generality of property injection is not very good.

3. Design Principle Issues: It is easier to violate a single design principle.

2.2 Setter Method Injection

Setter injection, write the setter method of the property to be injected, and then add the annotation @Autowired

2.2.1 Advantage Analysis

Compared to property injection, it is more in line with the single design principle

2.2.2 Shortcoming Analysis

1. Immutable objects (finally modified objects) cannot be injected;

2. The injected object can be modified: the injected object may be modified at any time

2.3 Constructor Injection

Write the constructor, pass the parameters into the object to be injected, and then write the annotation @AutoWired (if there is only one constructor in the current class, the annotation can be omitted)

2.3.1 Advantage Analysis

1. Immutable objects can be injected;

2. The injected object will not be modified: the constructor will only be executed once when the object is created, so it does not exist that the injected object is modified at any time (called).

3. The injected object will be fully initialized;

4. Better versatility: Constructor injection can be applied to any environment, whether it is an IoC framework or a non-IoC framework, the code injected by the constructor is common, so its versatility is better.

Note: Interview Question

The above implementation is a common interview question:
Interviewer: How many injection methods does Spring have? What are the differences between them

3. @Resource: another injection keyword

@Resource: supports property injection and Setter injection, but does not support constructor injection

3.1 Difference between @Autowired and @Resource

The same thing: they are all used to implement dependency injection.

Differences:
1. Different functional support: @Autowired supports attribute injection, setter injection, and constructor injection; @Resource supports attribute and setter injection, but does not support constructor injection

2. Different origins: @Autowired comes from Spring framework; @Resource comes from JDK.

3. Parameter support is different: @Resource supports more parameter settings; while @Autowired only supports required parameters.

4. Multiple @Bean errors of the same type

Workaround:

(1) Accurately describe the name of the bean (write the injected name correctly)

(2) Use @Resource to set the name to rename the injected object

(3) If @Autowired cannot be deleted, you can add @Qualifier to delete bean objects