自动连线的依存关系为空

时间:2019-04-24 13:07:08

标签: 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()方法被调用之前“注入”了Foo,但是当我在新计算机上构建并运行它时,情况似乎并非如此。我的猜测是,某种程度上使用了spring的不同版本,依赖注入的规则有所不同。

@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!
   }

}

1 个答案:

答案 0 :(得分:3)

您肯定有循环依赖,这绝对是一个不好的信号。您应该重新设计。我正在检查涵盖此主题的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部分的工作方式并从中汲取灵感:)。

关于为什么它在一台机器上可以运行而在另一台机器上不能运行,这对我来说还是个谜。