Spring Rest Controller inheritance
you can define an abstract method in your abstract class and autowire the correct service on each implementation :
public abstract class CookieApi<T extends Cookie> {
protected abstract CookieService<T> getCookieService();
@RequestMapping("/cookieId")
public void eatCookie(@PathVariable long cookieId) {
final T cookie = cookieService.findCookie(cookieId); // Cookie service is null
this.getCookieService().eatCookie(cookie);
}
}
@RestController
@RequestMapping("/chocolateCookies")
public class ChocolateCookieApi extends CookieApi<ChocolateCookie> {
@Autowired
private ChocolateCookie chocolateCookie;
@Override
protected CookieService<T> getCookieService() {
return this.chocolateCookie;
}
@PostMapping
public ResponseEntity<ChocolateCookie> create(@RequestBody ChocolateCookie dto) {
// TODO Process DTO and store the cookie
return ResponseEntity.ok(dto);
}
}
Nikola,
I'm not sure why your code is not working in your system, I created same classes in a project and it is working fine, I even added another Cookie type, service and api classes.
SpringBoot log (you can see 4 end points initialized):
2019-02-26 14:39:07.612 INFO 86060 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/chocolateCookies],methods=[POST]}" onto public org.springframework.http.ResponseEntity<cookie.ChocolateCookie> cookie.ChocolateCookieApi.create(cookie.ChocolateCookie)
2019-02-26 14:39:07.613 INFO 86060 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/chocolateCookies/{cookieId}],methods=[POST]}" onto public org.springframework.http.ResponseEntity<?> cookie.CookieApi.eatCookie(long)
2019-02-26 14:39:07.615 INFO 86060 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/oatmeal-raisin-cookie],methods=[POST]}" onto public org.springframework.http.ResponseEntity<cookie.OatmealRaisinCookie> cookie.OatmealRaisingCookieApi.create(cookie.OatmealRaisinCookie)
2019-02-26 14:39:07.615 INFO 86060 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/oatmeal-raisin-cookie/{cookieId}],methods=[POST]}" onto public org.springframework.http.ResponseEntity<?> cookie.CookieApi.eatCookie(long)
Testing controllers in postman
As @Domingo mentioned, you may have some configuration problems in your application because from OOP and Spring IoC perspectives your code looks fine and runs with no problems.
NOTE: I'm running these controllers using SpringBoot 2.0.5, Java 8, Eclipse
I posted my project in GitHub for your reference. https://github.com/karl-codes/cookie-monster
Cheers!