gpt4 book ai didi

java - Spring beans - 验证是否正确初始化

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

我正在为我的 Java 项目使用 Spring 框架。当我启动模块时,有时 spring bean 未正确初始化,并且 bean 将为 null 并且程序将出现异常(空指针异常)。有什么方法可以确保在启动期间所有 bean 都正确初始化吗?

最佳答案

Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to use constructors for mandatory dependencies and setter methods or configuration methods for optional dependencies. Note that use of the @Required annotation on a setter method can be used to make the property a required dependency.

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.

这样,如果您的 bean 是不可变对象(immutable对象),那么只需使用基于构造函数的 DI。如果它们不是不可变的,那么您可以结合基于构造函数和基于 setter 的 DI,或使用 @Required 注释。

关于java - Spring beans - 验证是否正确初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49397612/

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