SoFunction
Updated on 2025-03-08

In-depth analysis and practical guide for @Autowired annotation in Spring

Preface

In Spring framework,@AutowiredAnnotation is a very important annotation used to implement Dependency Injection (DI). pass@AutowiredAnnotation, Spring containers can automatically inject dependent beans into target beans, simplifying code and improving maintainability. This article will discuss in depth@AutowiredThe use of annotations helps you better understand its working principle and practical application.

1. Pre-knowledge: Dependency injection in Spring

In-depth discussion@AutowiredBefore annotating, we need to know some pre-emptive knowledge.

1.1 What is dependency injection?

Dependency injectionis a design pattern used to separate the dependencies of objects from the code and manage these dependencies through external containers such as Spring containers. Dependency injection makes the code more loosely coupled and easier to test and maintain.

1.2 Dependency injection method in Spring

The Spring framework provides a variety of dependency injection methods, including:

  • Constructor Injection
  • Setter Injection
  • Field Injection

2. Basic usage of @Autowired annotation

@AutowiredAnnotations are used to automatically inject dependant beans. You can use it on a constructor, Setter method or field@Autowiredannotation.

2.1 Constructor Injection

Constructor injection is the most recommended way to inject dependencies because it ensures that objects already have all the necessary dependencies when they are created.

@Service
public class MyService {

    private final MyRepository myRepository;

    @Autowired
    public MyService(MyRepository myRepository) {
         = myRepository;
    }

    public void doSomething() {
        ();
    }
}

In this example,MyServiceThe class is used through constructor injectionMyRepositoryBean. Spring container will automaticallyMyRepositoryBean injected intoMyServicemiddle.

2.2 Setter Injection

Setter injection uses Setter methods to inject dependencies. This way allows dynamic changes to dependencies after object creation.

@Service
public class MyService {

    private MyRepository myRepository;

    @Autowired
    public void setMyRepository(MyRepository myRepository) {
         = myRepository;
    }

    public void doSomething() {
        ();
    }
}

In this example,MyServiceThe class is used through Setter injectionMyRepositoryBean. Spring container will be called automaticallysetMyRepositoryMethod,MyRepositoryBean injected intoMyServicemiddle.

2.3 Field Injection

Field injection is used directly on the field@AutowiredAnnotation to inject dependencies. This approach is concise, but not recommended because it breaks the encapsulation and is difficult to unit test.

@Service
public class MyService {

    @Autowired
    private MyRepository myRepository;

    public void doSomething() {
        ();
    }
}

In this example,MyServiceThe class is used by field injectionMyRepositoryBean. Spring container will automaticallyMyRepositoryBean injected intoMyServicein the field.

3. Advanced usage of @Autowired annotation

@AutowiredAnnotations are not limited to simple dependency injection, but can also be configured and customized in a variety of ways.

3.1 Specify the name of the bean

By default, Spring containers automatically match dependent beans based on type. If there are multiple beans of the same type, you can@QualifierAnnotation specifies the name of the bean.

@Service
public class MyService {

    @Autowired
    @Qualifier("myRepository")
    private MyRepository myRepository;

    public void doSomething() {
        ();
    }
}

In this example,MyServiceClass passed@QualifierAnnotation specifiedmyRepositoryThe name of the bean avoids conflicts of multiple beans of the same type.

3.2 Using Optional Injection

You can passOptionalclass to implement optional dependency injection. If the dependency bean does not exist,OptionalWill be empty.

@Service
public class MyService {

    @Autowired
    private Optional<MyRepository> myRepository;

    public void doSomething() {
        (repository -> ());
    }
}

In this example,MyServiceClass passedOptionalThe class implements optional dependency injection. ifMyRepositoryBean does not exist,myRepositoryWill be empty.

3.3 Annotation with @Primary

If there are multiple beans of the same type, you can@PrimaryAnnotation specifies the default bean.

@Configuration
public class AppConfig {

    @Bean
    @Primary
    public MyRepository myRepository1() {
        return new MyRepositoryImpl1();
    }

    @Bean
    public MyRepository myRepository2() {
        return new MyRepositoryImpl2();
    }
}

@Service
public class MyService {

    @Autowired
    private MyRepository myRepository;

    public void doSomething() {
        ();
    }
}

In this example,AppConfigClass passed@PrimaryAnnotation specifiedmyRepository1Bean is the default bean.MyServiceClass passed@AutowiredAnnotation injectedmyRepository1 Bean。

3.4 Using @Lazy annotation

You can pass@LazyAnnotations implement delayed injection. Delay injection means that the dependent bean will be initialized only when used for the first time.

@Service
public class MyService {

    @Autowired
    @Lazy
    private MyRepository myRepository;

    public void doSomething() {
        ();
    }
}

In this example,MyServiceClass passed@LazyAnnotations implement delayed injection.myRepositoryThe bean will not be initialized when it is used for the first time.

4. Practical application scenarios

@AutowiredAnnotations have a wide range of application scenarios in actual projects, especially in scenarios where dependency injection is required.

4.1 Service layer injection

In the service layer, multiple dependency beans are usually required, such as repositories, configurations, etc.

@Service
public class MyService {

    @Autowired
    private MyRepository myRepository;

    @Autowired
    private MyConfig myConfig;

    public void doSomething() {
        ();
        ();
    }
}

In this example,MyServiceClass passed@AutowiredAnnotation injectedMyRepositoryandMyConfig Bean。

4.2 Controller layer injection

In the controller layer, it is usually necessary to inject the service layer beans.

@Controller
public class MyController {

    @Autowired
    private MyService myService;

    @GetMapping("/doSomething")
    public String doSomething() {
        ();
        return "success";
    }
}

In this example,MyControllerClass passed@AutowiredAnnotation injectedMyService Bean。

4.3 Configuration class injection

In configuration classes, other configuration classes or beans are usually required.

@Configuration
public class AppConfig {

    @Autowired
    private MyConfig myConfig;

    @Bean
    public MyService myService() {
        return new MyService(myConfig);
    }
}

In this example,AppConfigClass passed@AutowiredAnnotation injectedMyConfigBean, andmyServiceBean's definition is usedmyConfig

5. Summary

@AutowiredAnnotations are a very important annotation in the Spring framework, used to implement dependency injection. pass@AutowiredAnnotation, Spring containers can automatically inject dependent beans into target beans, simplifying code and improving maintainability. In actual projects,@AutowiredAnnotations are widely used in service layer, controller layer, configuration class and other scenarios.

Hope this article helps you understand better@AutowiredUse of annotations and apply it flexibly in actual projects.

This is all about this article about @Autowired annotation in Spring. For more related contents of @Autowired annotation in Spring, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!