Lantaros
Lantaros

Reputation: 146

How to autowire a Service with another Service's instance

I'm trying to invoke a function in a Service instance which is Autowired to another Service. Something structured like this:

public interface HomeService {
  
  public int fixRoof();

}

@Service
public class HomeServiceImpl implements HomeService {
  private FixRoofOpService fixRoofOpService;
  
  @Autowired
  HomeServiceImpl(FixRoofOpService fixRoofOpService) {
    this.fixRoofOpService = fixRoofOpService;
  }

  @Override
  public int fixRoof() {
    return this.fixRoofOpService();
  }
}

@Service
public class FixRoofOpService {
  public int execute() {
      return 3;
  }
}

@Service
public class MyDay {
  private HomeService homeService;
  
  @Autowired
  MyDay(HomeService homeService) {
    this.homeService = homeService;
  }

  private int someFunction() { 
    return this.homeService.fixRoof();
  }
}

While executing MyDay.someFunction() I get a NullPointerExeception when this.homeService.fixRoof() is called. I've verified that HomeService within MyDay is successfully injected. However, its fixRoof's reference is null. Thanks in advance!

Upvotes: 0

Views: 482

Answers (1)

Prakhar
Prakhar

Reputation: 102

The first mistake is in the HomeServiceImpl class. You are trying to return a object as a function. This itself should give you a compilation error

@Override
  public int fixRoof() {
    return this.fixRoofOpService();
  }

The below code works for me, please check if this helps you -

    public interface HomeService {
      public int fixRoof();
    }

    @Service
    public class HomeServiceImpl implements HomeService {
      @Autowired
      private FixRoofOpService fixRoofOpService;

      @Override
      public int fixRoof() {
        return fixRoofOpService.execute();
      }
    }

    @Service
    public class FixRoofOpService {
      public int execute() {
        return 3;
      }
    }

    @Service
    public class MyDay {
      @Autowired
      private HomeService homeService;

      public int someFunction() {
        return this.homeService.fixRoof();
      }
    }

Now when you @Autowire MyDay and call myDay.someFunction() you should get the value 3 in return.

Upvotes: 1

Related Questions