java - Autowiring 依赖项为空

标签 java spring-boot gradle

我有一个 spring-boot 项目,我已经能够在运行 Sierra 的旧 Mac 上成功运行该项目。我最近买了一台装有 Mojave 的新 Mac,当我构建 spring-boot 项目时,在尝试使用 @Autowired 依赖项时出现 NullpointerException 异常。

我已确保使用 gradle 包装器(版本 4.8)构建项目,并且两台计算机上都安装了相同版本的 java (1.8.0_60)。 build.gradle文件中定义的spring boot版本为1.5.5.RELEASE。

我意识到类 Foo 和 MyService 之间存在循环依赖关系,但这从来都不是问题。 MyService 应该在调用 Foo 的 init() 方法“之前”注入(inject) Foo,但当我在新计算机上构建并运行它时,情况似乎并非如此。我的猜测是,不知何故使用了不同版本的 spring,其中依赖注入(inject)的规则有所不同。

@Component
public class Foo {

   @Autowired
   private MyService service;

   @PostConstruct
   private void init() {
      service.doSomething();
   }

   public void bar() {}
}

@Component
public class MyService {

   @Autowired
   private Foo foo;

   public void doSomething() {
      foo.bar(); // <- NPE occurs here!
   }

}

最佳答案

存在循环依赖绝对是一个不好的迹象。你应该重新设计。我正在检查blog post其中涵盖了该主题,并介绍了以下有关循环依赖项的内容:

When you have a circular dependency, it’s likely you have a design problem 
and the responsibilities are not well separated. You should try to redesign 
the components properly so their hierarchy is well designed and there is no 
need for circular dependencies.

If you cannot redesign the components (there can be many possible reasons for 
that: legacy code, code that has already been tested and cannot be modified, 
not enough time or resources for a complete redesign…)...

如果您仍想保持原样,可以查看4.4 节。 @PostConstruct 他们是如何做到这一点的,并从中汲取灵感:)。

至于为什么它在一台机器上工作而在另一台机器上不起作用,对我来说是个谜。

关于java - Autowiring 依赖项为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55830793/

相关文章:

java - 使JList中的按钮可点击

spring-boot - 向Grails注册bean for MeterRegistryCustomizer

java - Spring Boot 错误 Controller 检索原始请求

java - 使用 Gradle 时如何忽略 Jacoco 中的内部静态类

java - 如何将旋转器中选取的文本放入字符串中并在其他类中使用

java - JH Labs 量化使用以减少图像颜色深度

java - 无法从 URL 获取输入流! java

amazon-web-services - 尝试在没有代理的情况下连接 Dynamo DB 时发生连接超时错误

gradle - 使用 Gradle 在 Kotlin 服务器和客户端项目之间共享代码

gradle - Delombok使用Gradle