gpt4 book ai didi

java - 如何正确设计Spring组件?

转载 作者:行者123 更新时间:2023-12-02 10:37:59 24 4
gpt4 key购买 nike

设计 Spring 组件有哪些基本建议?

主要用途:

  • 避免 NullPointerException
  • 单元测试的灵 active
  • 线程安全

恕我直言(基于 Spring 4 官方文档 https://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/beans.html#beans-constructor-injection (“基于构造函数或基于 setter 的 DI?”)):

  • 可选字段应具有默认值。如果需要,它们应该具有注释@Value(对于简单类型,如int、String等)或@Autowired对于复杂对象。
  • 必填字段应该是最终,并在带有@Autowired注释的唯一构造函数中声明。如果必填字段数量超过5个,建议重新设计类。构造函数中的每个参数都应该使用 @Nonnull 进行注释(例如 javax.annotation.Nonnull),并在内部进行 null 检查。
  • (?) 不推荐使用Set方法。尽管对于单元测试,您可以添加一些(但也许最好将此字段添加到构造函数中)。另外,应该使用@Nonnull和空检查。
  • (?) 也不建议使用 Get 方法(为什么要打开内部字段的传递访问?)

示例:

@Controller
@RequestMapping("/api/clients")
public final class ClientApiController {
// optional field with a default value (simple type)
@Value("${random.string.size}")
private final int randomStringSize = 256;

// optional field with a default value (complex type)
@Autowired
private final Charset defaultCharset = Charset.forName("UTF-8");

// required field
private final ClientService clientService;

// sole constructor with required fields and NULL check
@Autowired
public ClientApiController(@Nonnull ClientService clientService) {
Objects.requireNonNull(clientService, "clientService is null");
this.clientService = clientService;
}

// no Set and Get methods
}

最佳答案

我相信没有定义任何作用域的 spring Component 只是另一个类,在创建应用程序时只有一个实例,也称为 Singleton :) 。

只需确保注入(inject)的依赖项是使用构造函数完成的。这对于使用任何模拟框架进行单元测试都非常有帮助。

除此之外,只需遵循类所需的所有基本面向对象设计事实即可。 固体、干燥等.

希望这有帮助。干杯!!!

关于java - 如何正确设计Spring组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53138203/

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