0

I've used Spring Boot to develop a REST Service. In one of the REST controllers I have a field based dependency injection that I like to change to a constructor based dependency injection. My setup of the dependency injections currently looks like this:

@RestController
public class ParameterDateController {

    private ParameterDateController() {
    }

    private ParameterDate parameterDate;

    private ParameterDateController(ParameterDate parameterDate) {
        this.parameterDate = parameterDate;
    }

    @Autowired
    private ParameterDateService parameterDateService;

// here are the metods of the endpoints
}

With this setup everything works fine. I would likt to change ParameterDateService to constructor based and I tried with this:

@RestController
public class ParameterDateController {

    private ParameterDateController() {
    }

    private ParameterDate parameterDate;

    private ParameterDateController(ParameterDate parameterDate) {
        this.parameterDate = parameterDate;
    }

    private ParameterDateService parameterDateService;

    private ParameterDateController(ParameterDateService parameterDateService) {
        this.parameterDateService = parameterDateService;
    }

// here are the metods of the endpoints
}

After the change to constructor based dependency injection I get a NullPointerException when I try to inject the dependency like this parameterDateService.postParameterDate(parameterDate);. I inject the same way when I have it setup as field based dependency injection and that gives no NullPointerException. The constructor based dependency injection for ParameterDate works as expected.

What is it I'm doing wrong?

g3blv
  • 3,877
  • 7
  • 38
  • 51
  • 1
    You must add Autowired on the second constructor. Or remove the first one. You should also make it public: what's the point of a constructor you can't call without reflection? If you're happy with that, field injection is also fine. – JB Nizet Jun 10 '17 at 09:29

1 Answers1

0

If you want to have two dependencies wired via constructor - you have to declare them as constructor parameters, so here you have to declare:

public ParameterDateController(ParameterDate parameterDate, ParameterDateService parameterDateService) {
    this.parameterDate = parameterDate;
    this.parameterDateService = parameterDateService;
}

Here's a good answer about constructor injection.

ledniov
  • 2,302
  • 3
  • 21
  • 27