Preface
In Spring framework,@Autowired
Annotation is a very important annotation used to implement Dependency Injection (DI). pass@Autowired
Annotation, Spring containers can automatically inject dependent beans into target beans, simplifying code and improving maintainability. This article will discuss in depth@Autowired
The use of annotations helps you better understand its working principle and practical application.
1. Pre-knowledge: Dependency injection in Spring
In-depth discussion@Autowired
Before 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
@Autowired
Annotations are used to automatically inject dependant beans. You can use it on a constructor, Setter method or field@Autowired
annotation.
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,MyService
The class is used through constructor injectionMyRepository
Bean. Spring container will automaticallyMyRepository
Bean injected intoMyService
middle.
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,MyService
The class is used through Setter injectionMyRepository
Bean. Spring container will be called automaticallysetMyRepository
Method,MyRepository
Bean injected intoMyService
middle.
2.3 Field Injection
Field injection is used directly on the field@Autowired
Annotation 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,MyService
The class is used by field injectionMyRepository
Bean. Spring container will automaticallyMyRepository
Bean injected intoMyService
in the field.
3. Advanced usage of @Autowired annotation
@Autowired
Annotations 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@Qualifier
Annotation specifies the name of the bean.
@Service public class MyService { @Autowired @Qualifier("myRepository") private MyRepository myRepository; public void doSomething() { (); } }
In this example,MyService
Class passed@Qualifier
Annotation specifiedmyRepository
The name of the bean avoids conflicts of multiple beans of the same type.
3.2 Using Optional Injection
You can passOptional
class to implement optional dependency injection. If the dependency bean does not exist,Optional
Will be empty.
@Service public class MyService { @Autowired private Optional<MyRepository> myRepository; public void doSomething() { (repository -> ()); } }
In this example,MyService
Class passedOptional
The class implements optional dependency injection. ifMyRepository
Bean does not exist,myRepository
Will be empty.
3.3 Annotation with @Primary
If there are multiple beans of the same type, you can@Primary
Annotation 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,AppConfig
Class passed@Primary
Annotation specifiedmyRepository1
Bean is the default bean.MyService
Class passed@Autowired
Annotation injectedmyRepository1
Bean。
3.4 Using @Lazy annotation
You can pass@Lazy
Annotations 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,MyService
Class passed@Lazy
Annotations implement delayed injection.myRepository
The bean will not be initialized when it is used for the first time.
4. Practical application scenarios
@Autowired
Annotations 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,MyService
Class passed@Autowired
Annotation injectedMyRepository
andMyConfig
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,MyController
Class passed@Autowired
Annotation 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,AppConfig
Class passed@Autowired
Annotation injectedMyConfig
Bean, andmyService
Bean's definition is usedmyConfig
。
5. Summary
@Autowired
Annotations are a very important annotation in the Spring framework, used to implement dependency injection. pass@Autowired
Annotation, Spring containers can automatically inject dependent beans into target beans, simplifying code and improving maintainability. In actual projects,@Autowired
Annotations are widely used in service layer, controller layer, configuration class and other scenarios.
Hope this article helps you understand better@Autowired
Use 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!