No exemplo a baixo, estou tentando fazer um Serviço RestFul separando totalmente o @RestController, @Service e o @Repository. Mas estou com uma dificuldade, pois quando tento utilizar o service dentro do controller ele a instancia fica sempre NULL, sendo assim, ao tentar utilizar a mesma dá um NULL EXCEPTION.
Obrigatoriamente tenho que usar o repository dentro da controller, ou posso continuar a usar mais separadamente ?
Service
package com.pokemon.tcg.api.Services;
import com.pokemon.tcg.api.Models.Type;
import com.pokemon.tcg.api.Repositories.TypeRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.stereotype.Service;
@Service
@Configurable
public class TypeService {
@Autowired
TypeRespository typeRespository;
public void save(Type type){
typeRespository.save(type);
}
}
RestController
package com.pokemon.tcg.api.Controllers;
import com.pokemon.tcg.api.Models.Type;
import com.pokemon.tcg.api.Services.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/types")
public class TypeController {
@Autowired
private TypeService typeService;
@RequestMapping(value = "/save", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE )
@ResponseBody
public ResponseEntity save(@RequestBody Type type){
typeService.save(type);
return new ResponseEntity<>(type, HttpStatus.CREATED);
}
}
Repository
package com.pokemon.tcg.api.Repositories;
import org.springframework.data.repository.CrudRepository; import com.pokemon.tcg.api.Models.Type;
public interface TypeRespository extends CrudRepository { }