Autowired dependency is null

Refresh

April 2019

Views

37 time

0

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.

@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 answers

3

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.