亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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;
    }
}

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...
}

基于構(gòu)造函數(shù)注入的主要優(yōu)點(diǎn)是可以將需要注入的字段聲明為final, 使得它們會(huì)在類實(shí)例化期間被初始化,這對(duì)于所需的依賴項(xiàng)很方便。

2.2 基于Setter的依賴注入

在基于setter的依賴注入中,setter方法被標(biāo)注為 @Autowired。一旦使用無(wú)參數(shù)構(gòu)造函數(shù)或無(wú)參數(shù)靜態(tài)工廠方法實(shí)例化Bean,為了注入Bean的依賴項(xiàng),Spring容器將調(diào)用這些setter方法。

@Component
public class SetterBasedInjection {

    private InjectedBean injectedBean;

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

和基于構(gòu)造器的依賴注入一樣,在官方文檔中,基于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...
}

2.3 基于屬性的依賴注入

在基于屬性的依賴注入中,字段/屬性被標(biāo)注為 @Autowired。一旦類被實(shí)例化,Spring容器將設(shè)置這些字段。

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

正如所看到的,這是依賴注入最干凈的方法,因?yàn)樗苊饬颂砑訕影宕a,并且不需要聲明類的構(gòu)造函數(shù)。代碼看起來(lái)很干凈簡(jiǎn)潔,但是正如代碼檢查器已經(jīng)向我們暗示的那樣,這種方法有一些缺點(diǎn)。


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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

Hot Topics

PHP Tutorial
1488
72
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

Build desktop applications using Spring Boot and JavaFX Build desktop applications using Spring Boot and JavaFX Jun 22, 2023 am 10:55 AM

As technology continues to evolve, we can now use different technologies to build desktop applications. SpringBoot and JavaFX are one of the more popular choices now. This article will focus on how to use these two frameworks to build a feature-rich desktop application. 1. Introduction to SpringBoot and JavaFXSpringBoot is a rapid development framework based on the Spring framework. It helps developers quickly build web applications while providing a set of

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.

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

Using WebSocket in Spring Boot to implement push and notification functions Using WebSocket in Spring Boot to implement push and notification functions Jun 23, 2023 am 11:47 AM

In modern web application development, WebSocket is a common technology for instant communication and real-time data transfer. The SpringBoot framework provides support for integrated WebSocket, making it very convenient for developers to implement push and notification functions. This article will introduce how to use WebSocket to implement push and notification functions in SpringBoot, and demonstrate the implementation of a simple real-time online chat room. Create a SpringBoot project First, we need to create a

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

Spring Boot's task scheduling and scheduled task implementation methods Spring Boot's task scheduling and scheduled task implementation methods Jun 22, 2023 pm 11:58 PM

SpringBoot is a very popular Java development framework. It not only has the advantage of rapid development, but also has many built-in practical functions. Among them, task scheduling and scheduled tasks are one of its commonly used functions. This article will explore SpringBoot's task scheduling and timing task implementation methods. 1. Introduction to SpringBoot task scheduling SpringBoot task scheduling (TaskScheduling) refers to executing some special tasks at a specific point in time or under certain conditions.

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

See all articles