我有一个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节中的工作方式,并从中汲取灵感:)。

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

10-07 19:10
查看更多