[Spring] Use annotations to read and store Bean objects

 Hello, hello, everyone~ I am your old friend: protect Xiao Zhou ღ  


Speaking of frameworks in the Java circle, the oldest and most dazzling one is the Spring framework. This issue brings you:  storing objects in Spring, naming rules for Bean objects, obtaining bean objects from Spring, injecting keywords, the difference between @Autowired and @Resource, and solve the error of @Bean method annotation injecting multiple Bean objects of the same type. This article will explain it to everyone, let’s take a look~


This issue is included in the blogger's column : JavaEE_Protect Xiao Zhouღ's Blog-CSDN Blog

Suitable for programming beginners, interested friends can subscribe to view other "JavaEE Basics".

Stay tuned for more highlights: Protect Xiaozhou ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★*'


 1. Review of the previous period

We have implemented the most basic operations of reading and storing Bean objects in Spring, using Spring configuration files (.xml) to store Bean objects, using ApplicationContext or BeanFactory interfaces to obtain Spring context objects, and context objects manage Spring Bean object, and then call the getBean() method to obtain the specified Bean object. This method is an overloaded method. There are three main ways to obtain the Bean object:

1.  Obtain according to the id (flag) of the bean object 

2.  Get Bean according to the object type 

3. Get the bean according to  the id (flag) + type of the bean object

The first two methods of overloading to obtain the specified Bean object have their own defects, and we recommend using the third method.


After the previous study, although we have realized the basic acquisition and storage of Spring, the operation process is relatively cumbersome.

Storing Bean objects requires us to manually add configuration to the Spring configuration file.

To take out the Bean object, first we need to obtain the context object, and secondly, we need to call the getBean() method to obtain it according to the parameters. It is not as good as our traditional method, but there is one more (dependency inversion) idea.

So next we need to learn a simpler way to manipulate Bean objects - using annotations.

Use relevant annotations in Spring to store and read Bean objects.

Details:【Spring】Project Creation and Use_Protecting Xiao Zhouღ's Blog-CSDN Blog


2. Spring stores Bean objects

Before storing bean objects, we needed to add a line of bean tags to the Spring configuration file (.xml), as shown in the figure above.

Now what we need to learn is how to use annotations to replace the embarrassment of manually writing a line of bean configuration when adding Bean objects .

Annotation is a kind of metadata in the Java language, which provides a code-level marking mechanism to represent some structured information in the program and explain these structures. Annotations can be used on various Java program elements such as classes, fields, methods, parameters, etc., and annotation information can be obtained through the reflection mechanism.

Simple understanding:

Annotations are like labels, we can add them to the code of the program to add some additional information and instructions to the code. This information can help programs automate certain operations , such as code generation, configuration management, documentation generation, and more.

For example, if we want to add some configuration information to a class, usually we need to hand-write some configuration code in the code, and then parse and load it in the program. However, if we use annotations, we can let the program automatically complete the loading and parsing of the configuration by adding some specific annotations to the class . This saves a lot of time and code.

In short, annotation is a tool used to add additional information to the program, which can help us manage and automate various operations of the program more conveniently.


 2.1 Configure scan path

Before, we manually added the Bean object in the Spring configuration file (.xml). If we use the method of annotation to store, we only need to configure the package path where the bean object (not instantiated) is located. When Spring starts, the context object will be based on The path configured in the Spring configuration file is scanned, and only the classes and methods annotated in the path (package) can be correctly identified and instantiated into Spring.

The Spring configuration file (.xml) is configured as follows:

<?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="animal"></content:component-scan>
</beans>

If the annotated class or method is not under the package of the configuration scan, it cannot be stored in Spring.


2.2 Add annotations to store Bean objects

To store Bean objects in Spring more easily, there are two types of annotations:

1. Class annotation: As the name implies, it is an annotation used to modify the class, indicating that the modified class instance needs to be stored in the Spring container. Five categories of annotations: the meaning of these annotations is described in detail below

@Controller [controller], @Service [service], @Repository [warehouse], @Component [component],

@Configuratio [Configuration].

2. Method annotation: A method in a class can instantiate another class. At this time, set the return value of the method to the class object after the instance and then use the @Bean method annotation to store the object (bean object) in in the Spring container.

In Spring, the five major types of annotations can store Bean objects in Spring. There is not much to say , but in the learning of the framework later, each annotation hierarchically modifies the class, and their meaning is very particular. At this time, We mainly learn how to use annotations to access Bean objects, and other knowledge points will be expanded later.


2.2.1 @Controller (controller) stores Bean objects in Spring

First define a student class:

public class Student {
    // 属性
    private String id;
    private String name;
    private String sex;
    private int age;

    // 行为
    public void homework() {
        System.out.println(name + "在做作业~");
    }

    @Override
    public String toString() {
        return "student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                '}';
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

Add the @Controller annotation to the Student class to store the Student object (automatically at runtime) in Spring

1. Set the scanning path in the Spring configuration file

2. Add annotations to the Student class

It's very cool, just an annotation + set the scanning path to get it done~ When Spring starts, it will automatically add the Student class instance to Spring.

At this point we can use the method of getting the object before to try to get the object of the Student class from Spring.

The ApplicationContext interface obtains the context object, and then calls the getBean() method to obtain the specified Bean object.

public class App {
    public static void main(String[] args) {
        //1. 得到 Spring 的上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-test.xml");
        //2. 调用 getBean() 方法获取指定的 Bean 对象
        Student student = context.getBean("student",Student.class);

        //3. 使用 Bean 对象
        student.setId("1");
        student.setName("张三");
        student.setSex("男");
        student.setAge(20);

        student.homework();
        System.out.println(student.toString());
    }
}


2.2.1 @Service (service) stores Bean objects in Spring

The remaining three annotations @Repository [warehouse], @Component [component], @Configuratio [configuration]. It doesn't have much meaning in Spring, they all store Bean objects, and I won't show you that the results are the same here. Interested veterans can demonstrate it by themselves.


2.3 Why do we need so many class annotations?

As shown in the above example, the functions of the five types of annotations can store Bean objects in Spring. Why do we need so many class annotations when the functions are the same? ? ?

The specific application scenarios and meanings of each annotation:

1. @Controller annotation: [Controller] Verify the parameters transmitted by the front end [Security Inspection]

The Controller layer is part of the MVC (Model-View-Controller) design pattern and is responsible for handling user requests and controlling the flow of the application. It is a component in the application that receives requests from the user interface (View), coordinates the work of other components (such as the Service layer and the Repository layer), and returns the corresponding results to the user interface.

2. @Service annotation: [Service Layer]

It is mainly used to process business logic and perform specific business operations. It is located in the middle layer of the application, between the control layer and the data access layer, and is used to realize the encapsulation and processing of business logic.

3. @Repository annotation: [warehouse (data warehouse)] can be understood as directly operating the database

The Repository layer is a design pattern in software development that handles data access and persistence. In Java applications, the Repository layer is usually part of the data access layer, interacting with databases or other data storage media.

4. @Component annotation: [Component] general tool class

The Component layer is a componentized layer in Java applications, mainly used for component management and assembly. It is responsible for combining various functional modules or components to provide the overall functionality of the application. The Component layer is usually located at the top of the application and serves as the entry point of the application.

5. @Configuration annotation: [Configuration] Here are all the configurations of the project

The @Configuration annotation is used by the Spring Framework in addition to traditional XML configuration. In order to better support Java configuration, it represents a configuration class that can be used as a Bean definition after being annotated. Through the @Configuration annotation, you can easily configure the Bean components in the Spring container.

for example:

Each of us has a unique 18-digit ID number, which includes: area number, date of birth, sequence code and check code. The first few digits of the public ID numbers of the same province/city are the same. For example, the ID numbers of the new generation in Hubei Province all start with "42XXXX" . Among them, XXXX is a specific area code, which is used to represent different administrative divisions in Hubei Province. Yes, we can use a String type  region variable to describe the region code, so that we can intuitively see which region the people come from. The birthday variable can be used to describe a date of birth... To separate a complete ID number, It can express the basic information of this person more intuitively. It can be seen that the region variable describes the region. The old iron at the beginning of 42 is from Hubei. The class annotation is the same reason. I use different annotations for different "levels" of classes Description, is it very intuitive, for example: @Repository annotation is used to modify the class that operates the database according to the standard, which is very convenient for maintenance.

To sum up, although the functions of these five types of annotations can store Bean objects in Spring, their usage scenarios and semantics are slightly different, which can better meet different needs and scenarios. Because of this, there are so many types of annotations involved in the Spring framework to deal with different business scenarios and complex requirements.

The engineering layering of the program, the call flow chart:


2.3.1 Relationship between class annotations

Check the source code of @Controller / @Service / @Repository / @Configuration These annotations are found:

ctrl + mouse click on the annotation to view it.

There is a @Component annotation inside these annotations, indicating that these annotations can be considered as subclasses of @Component.


2.4 Naming rules for Bean objects

Above we store Bean objects by using annotations, which is to set the path (package) where the Bean objects are located in the Spring configuration article. When the Spring container starts, it will scan the path in the configuration file and instantiate the annotated class to in the container. If we use the old method to obtain the Bean object, we need to obtain the Spring context object (management bean) first. There are two ways [ApplicationContext interface] (officially recommended after Spring 3.x version), [BeanFactory interface]

After getting the context object, we need to call the getBean() method to get the specific Bean object, because the getBean() method has an overload, so there are three main ways to get it: 1. According to the Bean
object ID, we manually get the name (disadvantages,: The return value is Object, so it needs to be cast )

2. According to the type of the Bean object (disadvantage: if there are multiple beans of the same type stored in the container, an exception will be thrown at this time)

3. According to the ID of the Bean object and the type of the Bean object (recommended)

At this point we add Bean objects through class annotations, so what adjustments should be made to the method of obtaining Bean objects?

Usually, the Bean (class) is named using the standard big hump, and the Bean object can be obtained when the first letter is lowercase when reading:


When the first letter and the second letter of the class name are capitalized, the Bean cannot be read normally by using the default lowercase first letter:


Regarding the default ID of obtaining the Bean object, we need to understand the naming rules generated by Spring when storing the Bean object

Double-click the shift key to open the global search: Enter AnnotationbeanName

 The rule uses the decapitallze method in JDK introspector, the source code is as follows:

public static String decapitalize(String name) {
        if (name == null || name.length() == 0) {
            return name;
        }
        // 1. 如果第一个字母和第二个字母都为大写的情况,不做任何处理直接返回,也是就是id 是类名
        if (name.length() > 1 && Character.isUpperCase(name.charAt(1)) &&
                        Character.isUpperCase(name.charAt(0))){
            return name;
        }
        // 2. 否则就将首字母小写
        char chars[] = name.toCharArray();
        chars[0] = Character.toLowerCase(chars[0]);
        return new String(chars);
}

Summarize:

When registering a bean object using the five major types of annotations, the bean object is obtained (getBean() method) by default. You only need to lowercase the first letter of the class name as the parameter of the getBean() method; when the first letter of the class and the first letter of the class When the two first letters are capitalized, we need to use the original class name as the parameter of the getBean() method to get the bean object.

We can also manually perform naming operations on bean objects on class annotations:

[Class annotation] (value = "name")

Here's a concise way of writing it:

Expansion : If there is no directory in the project, how can all the classes be stored in the root directory of java, and how to get the bean object? ? ?

<content:component-scan base-package="**"></content:component-scan>

We can replace the file path with a wildcard "**" in the Spring configuration file. Using a wildcard means that after Spring starts, it will scan from the root directory to find those classes decorated with class annotations, and then instantiate these classes into the container . However, such a result will lead to slower execution speed and very low efficiency, so we suggest adding a suitable path to the project. 


2.5 Method annotation @Bean

Class annotations are added to a class. As the name suggests, method annotations are used to modify methods. The prerequisite for using method annotations (@Bean) is that objects need to be stored in the Spring container normally with class annotations, and the The return value of the method needs to be the same type as the expected storage Bean object :

@Component
public class StudentDemo {
    @Bean
    public Student getStu() {
        //1. 创建对象
        Student student = new Student();
        //2. 初始化对象
        student.setId("1");
        student.setName("李小四");
        student.setSex("男");
        student.setAge(18);
        //3. 返回对象
        return student;
    }
}

The function of the above code is that the StudengDemo class modified by the @Component annotation is scanned after Spring starts. Naturally, it needs to be instantiated into the Spring container. During the instantiation process, a @Bean annotation is found, which means that if you want to instantiate StudengDemo Class, then you have to modify the @Bean so that the Student object (Bean object) returned by the getStu() method is registered in Spring. The execution results are as follows:

At this point, we can make a slight modification to provide a construction method for the StudentDemo class and the Student class, so we can judge which class is loaded first? Note: We need to remove the class annotations on the Student class first, otherwise two bean objects will be stored in Spring, and the storage of multiple bean objects of the same type will be described below...

Note: By default, there is no default ID for storing Bean objects through method annotations, so we can manually set the ID (name) for Bean objects through type acquisition.

Conclusion: The method annotation @Bean can also register the object in Spring, provided that it needs to be used with the class annotation.

In the above code, the Student bean object registered by the @Bean method annotation needs to depend on the instance of the StudentDemo class. When we start Spring, the StudentDemo class will be loaded first, and the construction method will be executed. During the loading process, we find a need to execute the getStu() method ( Set properties), so first instance Student, and then instance StudentDemo, this one involves five stages of JVM loading classes - the life cycle of the Bean object, the next blog will tell you about it~~

Class A depends on Class B, so first, class B is instanced into Spring, and there is no annotation to dynamically extract the Bean object, so this example is not appropriate. I will talk about it later~~~


2.5.1 Bean object renaming

The @Bean annotation can be used to name the bean object by setting the name attribute:

 @Bean(name = "***")

name is actually an array, so a bean object can have multiple names:

@Bean(name = {"student", "李小四"})

 name = {} can also be omitted:

 @Bean({"student", "李小四"})

Note: When we give the Bean a name, the default name used cannot be used! ! !

The above is the whole content of storing bean objects in Spring by using annotations. If there is anything wrong, please criticize and correct


3. Spring gets the bean object

Obtaining a bean object is also called "object assembly" and "object injection", which means taking the object out and putting it into a certain class.

There are three ways to implement object assembly (object injection):

1. Property injection 2. Constructor injection 3. Setter injection

Next, the blogger will focus on three ways to tell you how Spring implements dynamic injection of bean objects (dynamically inject bean objects into a certain class at runtime).

3.1 Attribute injection

Attribute injection needs to be implemented using the  @Autowired annotation. Let me give you an example:

There is a student class (organization of student information), assuming that it corresponds to the student table in the database, there is a StuService class in the Service layer, this class can read student data from the database (addition, deletion, check and modification), and instantiate a complete student object , there is a StuController class, which can actually use the student data (call processing), so the StuController class needs to obtain the instance object of the StuService class to operate the student table in the database during operation. Of course, I will not show you how to use the database and write pseudo-code to simulate the real environment.

@Service
public class StuService {
    /**
     * 根据学生id从数据库中获取学生信息
     * @param id
     * @return
     */
    public Student getStu(String id) {
        //伪代码,链接数据库,查找学生信息
        Student stu = new Student();
        stu.setId(id);
        stu.setName("张三");
        stu.setAge(18);
        stu.setSex("男");
        return stu;
    }
}
@Controller
public class StuController {
    //1. 属性注入,从Spring 中取出 StuService 类型的bean 对象并注入到类引用中
    @Autowired
    private StuService stuService;

    //2. 调用注入的 bean 对象执行查询操作
    public Student getStu(String id) {
        return stuService.getStu(id);
    }
}

The method of getting getStu in the Controller: under normal circumstances, we convert the student information into json format, and the front-end sends a request, and the server responds, and sends the data (http protocol) to the front-end, and the front-end uses the data to build a page.

package school.student2;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import school.student.Student;

public class App {
    public static void main(String[] args) {
        //1. 得到 Spring 的上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-test.xml");
        //2. 调用 getBean() 方法获取指定的 Bean 对象
        StuController stuController = context.getBean("stuController", StuController.class);
        //3. 使用bean 对象
        Student student = stuController.getStu("1");
        System.out.println(student.toString());
    }
}

 The core of attribute injection:


3.2 Constructor injection

Constructor injection is to implement injection in the constructor of the class: also use the @Autowired annotation

 If there is only one constructor, the @Autowired annotation can be omitted:

If there are multiple constructors in the class, you need to add @Autowired to clearly specify which constructor to use, otherwise the program will report an error.


3.3 Setter injection

Setter essentially uses a custom method instead of constructor injection, and also needs to add the @Autowired annotation to the set method:

Note: When using Setter injection, you must add the @Autowired annotation


3.4 Analysis of advantages and disadvantages of three types of injection

3.4.1 Property Injection

Advantages: It is relatively simple to implement, only one @Autowired annotation is required

shortcoming:

1. Cannot inject immutable (final) objects

Final modified references can only be initialized and assigned at the time of creation, or initialized in the constructor.

 2. Only applicable to loC containers

Property injection is often closely associated with IoC (Inversion of Control) containers, and in most cases it is more commonly used in IoC containers. The IoC container hands over control to the framework by managing tasks such as object lifecycle, dependencies, and object creation to achieve decoupling and scalability. Generally speaking, property injection is closely related to IoC container, and when managing objects through IoC container, property injection is a common dependency injection method, which can help achieve code decoupling and configurability. However, in non-IoC scenarios, the use of property injection may be somewhat limited and may not be as suitable as other dependency injection methods.

3. Easier to violate the single design principle (for classes)

Property injection may violate the Single Responsibility Principle (SRP) in some cases. The goal of SRP is to ensure that a class has only one reason to change in order to improve code maintainability and flexibility. It emphasizes the division and separation of responsibilities, making each class focus on a single functionality or concern .

Here are some situations where property injection can lead to SRP violations:

  1. Too many dependencies: Property injection can cause a class to have too many dependencies. A class can take on too many responsibilities if it depends on too many other classes or components. Such classes can become large and difficult to understand and maintain.

  2. Diffusion of Responsibility: Property injection can cause a class to take on additional responsibilities that it should not have. When a class injects many properties, especially properties from different domains, it may participate in multiple responsibilities and business logic, thus violating SRP.

  3. Increased coupling: Property injection can lead to increased coupling between classes. If a class has too much control over the instantiation and configuration of its dependencies, its coupling to those dependencies increases. This makes extension and modification of the class more difficult.

While property injection may violate SRP in some cases, that doesn't mean property injection itself is wrong or should be avoided entirely. Proper use of property injection can avoid violating SRP by separating class responsibilities, decoupling dependencies, and keeping code maintainable. During the design and implementation process, the injected properties and dependencies should be carefully selected to ensure that they are consistent with the responsibilities and concerns of the class and avoid excessive complexity and coupling.


3.4.2 Constructor injection

advantage:

1. An immutable (final modification) object can be injected, and the constructor can assign a value to it.

 2. The injected object will not be modified

  • Can be modified by final (only one instance)
  • The constructor is executed only once with class loading

3. Better versatility

Through constructor injection, class dependencies can be clearly expressed, and constructor injection allows dependencies to be passed in during the instantiation phase of the class. This means that during the instantiation of the class, you can clearly see which objects the class depends on, instead of performing dependency injection when the method is called.

shortcoming:

No property injection implementation simple.

It should be noted that constructor injection is not suitable for all situations, especially when there are many dependent objects, there will be a problem of lengthy constructor parameter lists. In this case, you can consider using other forms of dependency injection, such as property injection or method injection, to provide a more flexible injection method. Choosing the appropriate dependency injection method depends on the specific situation and project requirements.

Constructor injection is the injection method officially recommended by Spring.


3.4.3 Setter method injection (ordinary method injection)

Setter methods are the recommended injection method for earlier versions of Spring.

Advantages: It is more in line with the single design principle (SRP). The method is aimed at the method level. Although it is not as strong as the construction method in terms of versatility, the Setter method injection also has its applicable scenarios, such as optional dependencies or dynamic changes. dependencies. In these cases, setter method injection may be more flexible and convenient . Choosing an appropriate dependency injection method requires trade-offs and judgments based on specific requirements and design principles.

shortcoming:

1. Immutable (final) objects cannot be injected;

Final modified references can only be initialized and assigned at the time of creation, or initialized in the constructor.

2. The injected object can be modified

The set method is an ordinary method that can be called repeatedly, and there is a risk of being modified when it is called. The current version of Spring has recommended the use of constructor injection for class injection.


3.5 @Resource Injection

When performing class injection in Java, in addition to using the @Autowired annotation, you can also use the @Resource annotation
:

 @Autowired and  @Resource are both annotations used in Java for dependency injection, but they have some differences.


3.5.1 The difference between @Autowired and @Resource

  1. Birth is different: @Autowired annotation comes from Spring framework (unofficial), @Resource annotation comes from JDK (official).
  2. Function support is different: @Autowired can be used for attribute injection, constructor injection, and Setter (ordinary method) injection. @Resoure can only be used for Setter injection and attribute injection, but not for constructor injection (meaning immutable objects cannot be injected ).
  3. The parameter support is different:  @Resource supports more parameter settings, for example: take a name for the Bean (name), while @Autowired can only be set  as  an optional attribute of the annotation, and the default value is  . It is used to specify whether dependency injection is required. When   the property is set  to  , an exception will be thrown if no matching dependent object can be found. required 参数。required@Autowired truerequired trueNoSuchBeanDefinitionException 

Example:

@Autowired(required = true)
private MyDependency myDependency;

When  required the property is set false to  , the dependent object will be set to if no matching dependent object is found null, i.e. allowing the optionality of dependency injection.

Example:

@Autowired(required = false)
private MyDependency myDependency;

Although  required the default is true , in some cases we may  @Autowired(required = false) mark optional dependency injection with , so that no exception is thrown when there is no matching dependent object. This is useful in scenarios where optional dependencies or dynamic injection are required.


3.6 Error handling when @Bean injects multiple bean objects of the same type

When we use the @Bean method annotation to inject multiple Bean objects of the same type into Spring, an error will be reported.

Note: In the previous examples, we need to comment the path in the Spring configuration file, otherwise multiple bean objects (stu) of the same type will be registered in the Spring container at startup.

@Component
public class StudentDemo {
    StudentDemo() {
        System.out.println("StudentDemo 执行");
    }
    @Bean
    public Student getStu() {
        //1. 创建对象
        Student student = new Student();
        //2. 初始化对象
        student.setId("1");
        student.setName("李小四");
        student.setSex("男");
        student.setAge(18);
        //3. 返回对象
        return student;
    }

    @Bean
    public Student getStu2() {
        //1. 创建对象
        Student student = new Student();
        //2. 初始化对象
        student.setId("2");
        student.setName("王小五");
        student.setSex("男");
        student.setAge(20);
        //3. 返回对象
        return student;
    }
}

Get the Student object in another class:

public class StudentApp {
    public static void main(String[] args) {
        //1. 得到 Spring 的上下文对象
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-test.xml");
        //2. 调用 getBean() 方法获取指定的 Bean 对象
        StudentController stuController = context.getBean(StudentController.class);

        //3. 利用 stuController 对象的 getStudent()获取 bean 对象
        Student student = stuController.getStudent();
        System.out.println(student.toString());
    }
}

@Controller
class StudentController {

    //1. 注入 student 对象,在StudentDemo 类中我们使用 @Bean 注入了两个stu 对象
    @Autowired
    private Student student;

    //2. 返回
    public Student getStudent() {
        return student;
    }
}

The result of the above program execution:

Error handling for multiple beans of the same type: 

  • When using Resoure(name = "FunctionName") for class injection, you can only specify the name of the @Bean annotation modification method. In this way, the problem is solved~
  • Use the @Qualifier annotation to define the name, which can be used in conjunction with the @Autowired annotation (Autowired annotations cannot specify name injection).

1. Use @Resource(name = "XXXXX") to define

2. Using @Qualifier 

The @Qualifier annotation  is used to help specify specific dependency injection or autowiring. It is often used with dependency injection frameworks such as Spring to resolve ambiguity among multiple candidates. In dependency injection, when there are multiple beans of the same type, the @Qualifier annotation can be used to identify the specific bean to be used. By specifying a unique identifier (name) in the @Qualifier annotation, you can tell the dependency injection framework which specific bean to inject.


 Four. Summary

1. Store the object in Spring:

  • The older method is to add annotations directly under the <Beans> </Beans> tag of the Spring configuration file.

The bad point is that it is more troublesome. Each Bean object needs to be added manually, and we have an annotation method for this.

  • Use class annotations: @Controller, @Service, @Repository, @Configuration, @Component and other annotations have a @Component annotation inside, indicating that these annotations can be considered as subclasses of @Component .

Use class annotations: You need to set the package scanning path in the Spring configuration file. When Spring starts, it will inject the modified class instance into Spring according to the class annotations under the package path. The class needs to be used directly with the scanning path, otherwise it cannot be successfully injected ( Here is a singleton mode, a class has only one instance).

  • Use method annotation @Bean [Note: must be used together with class annotation]

2. Naming rules for Bean objects

The first letter of the class is uppercase, the first letter of the class is lowercase, and the second letter is lowercase. By default, the bean is obtained by using the first letter of the lowercase as the name; if the first letter of the class and the second letter are both uppercase, then use the original class name directly. Get the Bean as name.

3. Get the bean object from Spring:

  • attribute injection 
  • Constructor injection (official recommendation)
  • Setter injection

 4. Injected keywords:

@Autowired and @Resource

5. The difference between @Autowired and @Resource:

  • Born differently: Autowired comes from Spring, Resource comes from JDK
  • Different parameters: @Resource supports more parameters, for example, you can name the Bean object when obtaining it
  • Different functions: @Autowired supports property injection, constructor injection and Setter method injection, while @Resource only supports property injection and Setter method injection.

6. Solve the error of @Bean method annotation injecting multiple Bean objects of the same type:

  • Use @Resource(name="method name")
  • Use @Qualifier (value = "method name")

Well, here we go, [Spring] Bloggers have finished sharing  using annotations to read and store Bean objects  . I hope it will be helpful to everyone. If there is anything wrong, please criticize and correct.

Next issue preview: Bean scope and life cycle

Thank you to everyone who read this article, and more exciting events are coming: Protect Xiaozhou ღ *★,°*:.☆( ̄▽ ̄)/$:*.°★* 

When I met you, all the stars fell on my head ...

Guess you like

Origin blog.csdn.net/weixin_67603503/article/details/131402330