gpt4 book ai didi

spring - Spring 中 Autowiring 的方法 - 下面两种可能的替代方案之间的区别

转载 作者:行者123 更新时间:2023-12-02 09:58:06 25 4
gpt4 key购买 nike

我有一个基本的自动接线问题。我看到 Spring Autowiring 中可能有以下两种实现

方法1

public class SimpleMovieLister {

private MovieFinder movieFinder;

@Autowired
public void setMovieFinder(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}

方法2

public class SimpleMovieLister {

@Autowired
private MovieFinder movieFinder;
}

我的理解是两者是相同的,并且我在代码中使用了很多 Method2。方法1在什么情况下有用?或者这只是 Spring 演变的一个例子,我们有两种可能的实现方式。

抱歉,如果这个问题太基本了,但我需要澄清一下

最佳答案

方法 1 是 Setter注入(inject)。

方法 2 是现场注入(inject)。

第三种方法是 Constructor注入(inject)

示例:

public class SimpleMovieLister {

private MovieFinder movieFinder;

@Autowired
public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
// ...
}

方法 3,构造函数注入(inject)是首选,因为它使测试变得更加容易,因为您可以传入所需的依赖项。

此外,如果您的 Bean 只有 1 个构造函数,那么您可以省略 @Autowired 注解。 Spring 在创建 bean 时会自动选择构造函数方法。

来自docs的一个很好的片段:

The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null. Furthermore constructor-injected components are always returned to client (calling) code in a fully initialized state. As a side note, a large number of constructor arguments is a bad code smell, implying that the class likely has too many responsibilities and should be refactored to better address proper separation of concerns.

Setter injection should primarily only be used for optional dependencies that can be assigned reasonable default values within the class. Otherwise, not-null checks must be performed everywhere the code uses the dependency. One benefit of setter injection is that setter methods make objects of that class amenable to reconfiguration or re-injection later. Management through JMX MBeans is therefore a compelling use case for setter injection.

Use the DI style that makes the most sense for a particular class. Sometimes, when dealing with third-party classes for which you do not have the source, the choice is made for you. For example, if a third-party class does not expose any setter methods, then constructor injection may be the only available form of DI.

关于spring - Spring 中 Autowiring 的方法 - 下面两种可能的替代方案之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45440798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com