SoFunction
Updated on 2025-04-08

Detailed explanation of example using @Autowired and @Bean annotations in Spring Boot

Using @Autowired and @Bean annotations in Spring Boot

In Spring Boot, Dependency Injection (DI) is done through@AutowiredImplemented by annotations, it can effectively simplify the dependencies between objects. At the same time, use@BeanAnnotations can help us explicitly define and initialize beans in configuration classes. This article will use a specific example to demonstrate how to use it in Spring Boot@Autowiredand@BeanTo manage the bean.

Sample background

Suppose we have oneStudentclass, and want to configure the classTestConfigTo initializeStudentObject, then passed in the test class@AutowiredAnnotations automatically inject and use it.

1. Define the Student class

First, we define a simpleStudentClass, use@DataAnnotations to generate common Getters, Setters,toStringetc.

import ;
@Data
public class Student {
    private String name;
}

On the aboveStudentIn the category,@DataThe annotation comes from Lombok, which automatically generates all the Getters, Setters andtoStringetc. In this way, we don't need to manually write these common codes, making the code more concise.

2. Configuration class: Initialize Bean

Next, we need to create a configuration classTestConfig, which defines a@BeanAnnotation method to initializeStudentObject.

import ;
import ;
@Configuration
public class TestConfig {
    @Bean
    public Student studentInit() {
        Student student = new Student();
        ("initialization");
        return student;
    }
}
  • @ConfigurationAnnotation means that the class is a configuration class, and Spring scans the class and initializes the bean according to its bean definition.
  • @BeanAnnotations are used to tell Spring containers:studentInit()The object returned by the method (here isStudent) should be managed as a bean. so,StudentThe object will become a management object in the Spring container.

In this configuration class, we explicitly initialize aStudentobject, and set itnameThe attribute is"initialization"

3. Test class:

use@AutowiredAutomatic annotation injection bean

In the test class, we will pass@AutowiredThe annotation willStudentObjects are automatically injected and outputStudentThe name.

import ;
import ;
import ;
@SpringBootTest
public class StudentTest {
    @Autowired
    private Student student;
    @Test
    void contextLoads13() {
        (()); // Output: Initialization    }
}
  • @SpringBootTestAnnotation means that this is a Spring Boot test class that starts the Spring container for integration testing.
  • @AutowiredAutomatic annotation injectionStudentBean. Spring will automatically find the type that matches itStudentBean and inject into this field.
  • In the test methodcontextLoads13()In, call()OutputStudentThe object'snameAttribute value should be output"initialization", this is with usTestConfigThe values ​​defined in the same way.

4. Automatic assembly of Spring Boot

  • In this example, we see that@AutowiredAnnotation, Spring container willStudentThe type automatically injects us with the right bean. No manual configuration or instance creation is required.
  • This automatic injection mechanism is a very powerful feature in Spring Framework, which can greatly simplify the management of dependencies between classes.

5. Summary

Through the above examples, we learned the following points:

  • @BeanAnnotation: Through this annotation, we can explicitly define beans in the configuration class so that the object is managed by the Spring container.
  • @AutowiredAnnotation: Through this annotation, Spring will automatically inject beans into places where they need to depend on according to their type.
  • @DataNote: SimplifiedStudentClass code does not require manual writing of Getter, Setter and other methods.

In actual development, Spring's dependency injection (DI) function greatly reduces the coupling between classes, improving the maintainability and scalability of the code. By using flexible@Autowiredand@BeanAnnotation can effectively manage and share objects.

This is the article about using `@Autowired` and `@Bean` annotations in Spring Boot. For more related springboot @Autowired and @Bean annotations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!