简体   繁体   English

Spring bean - 验证是否正确初始化

[英]Spring beans - Verify Properly Initialized

I'm using Spring frameworks for my Java Project.我在我的 Java 项目中使用 Spring 框架。 When I start the module sometimes spring beans are not correctly initialized and the bean will be null and program will have exception (Null Pointer Exception) .当我启动模块时,有时 spring bean 未正确初始化并且 bean 将为 null 并且程序将出现异常 (Null Pointer Exception) 。 Is there any way to make sure that during start up all the beans are initialized properly?有没有办法确保在启动期间所有 bean 都正确初始化?

There is a @Required annotation in spring. spring中有@Required注解。 This will make sure that the dependencies are present before initializing the beans.这将确保在初始化 bean 之前存在依赖项。 If the dependencies are not present it will throw error before initializing beans.如果依赖项不存在,它将在初始化 bean 之前抛出错误。 Use this in your code and try again.在您的代码中使用它并重试。 If you are still facing issues please post your code here.如果您仍然遇到问题,请在此处发布您的代码。

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.由于您可以混合使用基于构造函数和基于 setter 的 DI,因此根据经验,对强制依赖项使用构造函数,对可选依赖项使用 setter 方法或配置方法是一个很好的经验法则。 Note that use of the @Required annotation on a setter method can be used to make the property a required dependency.请注意,在 setter 方法上使用 @Required 注释可用于使属性成为必需的依赖项。

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. Spring 团队通常提倡构造函数注入,因为它可以将应用程序组件实现为不可变对象,并确保所需的依赖项不为空。 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.作为旁注,大量的构造函数参数是一种糟糕的代码味道,这意味着该类可能有太多的责任,应该重构以更好地解决适当的关注点分离问题。

In that way, If your beans are immutable objects then just use constructor-based DI.这样,如果您的 bean 是不可变对象,那么只需使用基于构造函数的 DI。 If they not immutable then you can combine constructor-based and setter-based DI, or use @Required annotation.如果它们不是不可变的,那么您可以结合基于构造函数和基于 setter 的 DI,或使用 @Required 注释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM