Table of Contents
1. Description" >1. Description
2.1 Constructor-based dependency injection" >2.1 Constructor-based dependency injection
2.2 基于Setter的依赖注入" >2.2 基于Setter的依赖注入
2.3 基于属性的依赖注入" >2.3 基于属性的依赖注入
3.2 It is easy to violate the single responsibility design principle" >3.2 It is easy to violate the single responsibility design principle
3.3 Tightly coupled with the dependency injection container" >3.3 Tightly coupled with the dependency injection container
3.4 Hiding dependencies" >3.4 Hiding dependencies
Home Java javaTutorial Why do big companies ban the use of @Autowired annotation in Spring Boot projects?

Why do big companies ban the use of @Autowired annotation in Spring Boot projects?

Aug 15, 2023 pm 04:00 PM
spring boot

1. Description


##The company recently upgraded the framework from the original spring framerwork 3.0<span style="outline: 0px;font-size: 16px;visibility: visible;"></span> upgraded to 5.0<span style="outline: 0px;font-size: 16px;visibility: visible;"></span>, and then suddenly discovered when writing code Idea gives a warning prompt on the @Autowired annotation for attribute injection, like the one below, which is quite confusing. After all, it has been written like this for many years.

Field injection is not recommended

Why do big companies ban the use of @Autowired annotation in Spring Boot projects?

I checked the relevant documents and found out that this prompt started to appear after <span style="outline: 0px;font-size: 16px;visibility: visible;">spring framerwork 4.0</span>. It is not recommended starting from spring 4.0. Use property injection, constructor injection and setter injection are recommended instead.

The following will show the different types of dependency injection that can be used by the spring framework, and the applicable situations of each dependency injection.


2. Type of dependency injection

Although for <span style="outline: 0px;font-size: 16px;">The documentation for spring framerwork 5.1.3</span> only defines two main types of dependency injection, but there are actually three;

  • Constructor-based dependency injection
  • Setter-based dependency injection
  • Field-based dependency injection

Among them<span style="outline: 0px;font-size: 16px;">Field-based dependency injection</span> is widely used, but idea or other static code analysis tools will give prompt messages and are not recommended.

You can even see this injection method in some official Spring guides:

Why do big companies ban the use of @Autowired annotation in Spring Boot projects?

2.1 Constructor-based dependency injection

In constructor-based dependency injection, the class constructor is marked @Autowired and contains many objects to be injected related parameters.

@Component
public class ConstructorBasedInjection {

    private final InjectedBean injectedBean;

    @Autowired
    public ConstructorBasedInjection(InjectedBean injectedBean) {
        this.injectedBean = injectedBean;
    }
}
Copy after login

Then in the spring official documentation, the @Autowired annotation can also be omitted.

public class SimpleMovieLister {

    // the SimpleMovieLister has a dependency on a MovieFinder
    private MovieFinder movieFinder;

    // a constructor so that the Spring container can inject a MovieFinder
    public SimpleMovieLister(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

    // business logic that actually uses the injected MovieFinder is omitted...
}
Copy after login

基于构造函数注入的主要优点是可以将需要注入的字段声明为final, 使得它们会在类实例化期间被初始化,这对于所需的依赖项很方便。

2.2 基于Setter的依赖注入

在基于setter的依赖注入中,setter方法被标注为 @Autowired。一旦使用无参数构造函数或无参数静态工厂方法实例化Bean,为了注入Bean的依赖项,Spring容器将调用这些setter方法。

@Component
public class SetterBasedInjection {

    private InjectedBean injectedBean;

    @Autowired
    public void setInjectedBean(InjectedBean injectedBean) {
        this.injectedBean = injectedBean;
    }
}
Copy after login

和基于构造器的依赖注入一样,在官方文档中,基于Setter的依赖注入中的 @Autowired也可以省去。

public class SimpleMovieLister {

    // the SimpleMovieLister has a dependency on the MovieFinder
    private MovieFinder movieFinder;

    // a setter method so that the Spring container can inject a MovieFinder
    public void setMovieFinder(MovieFinder movieFinder) {
        this.movieFinder = movieFinder;
    }

    // business logic that actually uses the injected MovieFinder is omitted...
}
Copy after login

2.3 基于属性的依赖注入

在基于属性的依赖注入中,字段/属性被标注为 @Autowired。一旦类被实例化,Spring容器将设置这些字段。

@Component
public class FieldBasedInjection {
    @Autowired
    private InjectedBean injectedBean;
}
Copy after login

正如所看到的,这是依赖注入最干净的方法,因为它避免了添加样板代码,并且不需要声明类的构造函数。代码看起来很干净简洁,但是正如代码检查器已经向我们暗示的那样,这种方法有一些缺点。


3. Field-based dependency injection defects

3.1 Immutable fields are not allowed to be declared

Field-based dependency injection does not work on fields declared as final/immutable because these fields must Instantiated when the class is instantiated. The only way to declare immutable dependencies is to use constructor-based dependency injection.

3.2 It is easy to violate the single responsibility design principle

##In object-oriented programming, the five design principles SOLID are widely used application, (generally six design principles in China) to improve code reusability, readability, reliability and maintainability

S ​​inSOLID represents the single responsibility principle, that is, a class should only be responsible for one responsibility, and all services provided by this class should only serve the responsibility it is responsible for.

Using field-based dependency injection, for frequently used classes, over time, we will gradually add more and more dependencies to the class. We are very happy to use it, and it is easy to ignore the class. There are already too many dependencies. But if you use constructor-based dependency injection, as more and more dependencies are added to the class, the constructor will become larger and larger, and we can tell something is wrong at a glance.

Having a constructor with more than 10 parameters is a clear sign that the class has transformed into a large and comprehensive collection of functions and needs to be divided into smaller and easier Maintained blocks.

So, although property injection is not a direct cause of breaking the single responsibility principle, it hides signals and makes it easy for us to ignore them.

3.3 Tightly coupled with the dependency injection container

The main reason to use field-based dependency injection is to avoid getters and setter's boilerplate code or create a constructor for the class. Ultimately, this means that the only way to set these fields is to instantiate the class through the Spring container and inject them using reflection, otherwise the fields will remain null.

The Dependency Injection design pattern separates the creation of class dependencies from the class itself and transfers this responsibility to the class injection container, allowing program design to be decoupled and adhere to a single responsibility and the dependency inversion principle (equally reliable). Therefore, the decoupling of the class achieved by autowiring fields is eventually lost by coupling it again to the class injection container (Spring in this case), thus rendering the class useless outside the Spring container.

This means that if you want to use your class outside the application container, for example for unit testing, you will be forced to use the Spring container to instantiate your class because there is no other possible way (except reflection) to set autowiring fields.

3.4 Hiding dependencies

When using dependency injection, the affected classes should be made clear using the public interface Expose these dependencies by exposing required dependencies in the constructor or optional dependencies using methods (setters). When using field-based dependency injection, these dependencies are essentially hidden from the outside world.


4. Summary

We have See, field-based injection should be avoided whenever possible because it has many disadvantages, no matter how elegant it looks. The recommended approach is to use constructor-based and setter-based dependency injection.

For required dependencies, it is recommended to use constructor-based injection, make them immutable, and prevent them from being null. For optional dependencies, it is recommended to use setter-based injection.

The above is the detailed content of Why do big companies ban the use of @Autowired annotation in Spring Boot projects?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Spring Boot+MyBatis+Atomikos+MySQL (with source code) Spring Boot+MyBatis+Atomikos+MySQL (with source code) Aug 15, 2023 pm 04:12 PM

In actual projects, we try to avoid distributed transactions. However, sometimes it is really necessary to do some service splitting, which will lead to distributed transaction problems. At the same time, distributed transactions are also asked in the market during interviews. You can practice with this case, and you can talk about 123 in the interview.

Achieve multi-language support and international applications through Spring Boot Achieve multi-language support and international applications through Spring Boot Jun 23, 2023 am 09:09 AM

With the development of globalization, more and more websites and applications need to provide multi-language support and internationalization functions. For developers, implementing these functions is not an easy task because it requires consideration of many aspects, such as language translation, date, time and currency formats, etc. However, using the SpringBoot framework, we can easily implement multi-language support and international applications. First, let us understand the LocaleResolver interface provided by SpringBoot. Loc

How to use Spring Boot to build big data processing applications How to use Spring Boot to build big data processing applications Jun 23, 2023 am 09:07 AM

With the advent of the big data era, more and more companies are beginning to understand and recognize the value of big data and apply it to business. The problem that comes with it is how to handle this large flow of data. In this case, big data processing applications have become something that every enterprise must consider. For developers, how to use SpringBoot to build an efficient big data processing application is also a very important issue. SpringBoot is a very popular Java framework that allows

How to use Spring Boot to build blockchain applications and smart contracts How to use Spring Boot to build blockchain applications and smart contracts Jun 22, 2023 am 09:33 AM

With the rise of digital currencies such as Bitcoin, blockchain technology has gradually become a hot topic. Smart contracts can be regarded as an important part of blockchain technology. SpringBoot, as a popular Java back-end development framework, can also be used to build blockchain applications and smart contracts. This article will introduce how to use SpringBoot to build applications and smart contracts based on blockchain technology. 1. SpringBoot and blockchain First, we need to understand some basic concepts related to blockchain. Blockchain

Implement ORM mapping based on Spring Boot and MyBatis Plus Implement ORM mapping based on Spring Boot and MyBatis Plus Jun 22, 2023 pm 09:27 PM

In the development process of Java web applications, ORM (Object-RelationalMapping) mapping technology is used to map relational data in the database to Java objects, making it convenient for developers to access and operate data. SpringBoot, as one of the most popular Java web development frameworks, has provided a way to integrate MyBatis, and MyBatisPlus is an ORM framework extended on the basis of MyBatis.

Integration and use of Spring Boot and NoSQL database Integration and use of Spring Boot and NoSQL database Jun 22, 2023 pm 10:34 PM

With the development of the Internet, big data analysis and real-time information processing have become an important need for enterprises. In order to meet such needs, traditional relational databases no longer meet the needs of business and technology development. Instead, using NoSQL databases has become an important option. In this article, we will discuss the use of SpringBoot integrated with NoSQL databases to enable the development and deployment of modern applications. What is a NoSQL database? NoSQL is notonlySQL

Distributed data caching and storage system based on Spring Boot Distributed data caching and storage system based on Spring Boot Jun 22, 2023 am 09:48 AM

With the continuous development and popularization of the Internet, the demand for data processing and storage is also increasing. How to process and store data efficiently and reliably has become a hot topic among industry and researchers. The distributed data caching and storage system based on SpringBoot is a solution that has attracted much attention in recent years. What is a distributed data caching and storage system? Distributed data caching and storage system refers to the distributed storage of data through multiple nodes (servers), which improves the security and reliability of data, and can also improve data processing.

Building an ESB system using Spring Boot and Apache ServiceMix Building an ESB system using Spring Boot and Apache ServiceMix Jun 22, 2023 pm 12:30 PM

As modern businesses rely more and more on a variety of disparate applications and systems, enterprise integration becomes even more important. Enterprise Service Bus (ESB) is an integration architecture model that connects different systems and applications together to provide common data exchange and message routing services to achieve enterprise-level application integration. Using SpringBoot and ApacheServiceMix, we can easily build an ESB system. This article will introduce how to implement it. SpringBoot and A

See all articles