Autowired dependency is null


April 2019


37 time


I have a spring-boot project that I have been able to run successfully on my older mac running Sierra. I recently bought a new mac with Mojave on it, and when I build the spring-boot project I get a NullpointerException when trying to use an @Autowired dependency.

I've made sure that I'm building the project using the gradle wrapper (version 4.8) and that the same version of java is installed on both machines (1.8.0_60). The spring boot version defined in the build.gradle file is 1.5.5.RELEASE.

I realize there is a circular dependency between classes Foo and MyService, but this has never been a problem. MyService should have Foo injected ''before'' Foo's init() method is called, but it doesn't seem to be the case when I build and run it on the new computer. My guess is that somehow a different version of spring is being used, where the rules for dependency injection are somehow different.

public class Foo {

   private MyService service;

   private void init() {

   public void bar() {}

public class MyService {

   private Foo foo;

   public void doSomething() {; // <- NPE occurs here!


1 answers


It is definitely a bad sign that you have a circular dependency. You should redesign. I was checking a blog post that covers this topic and it says the following about circular dependencies:

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…)...

If you still want to keep it the way it is, you can check section 4.4. @PostConstruct of how they are doing it and take inspiration from it :).

As to why it works on one machine and it doesn't on the other, is a mystery to me.