In the example below, I'm trying to do a RestFul Service by completely separating the @RestController, @Service, and @Repository. But I have a difficulty, because when I try to use the service inside the controller, the instance is always NULL, so when trying to use it it gives a NULL EXCEPTION.
Must I use the repository inside the controller, or can I continue to use more separately?
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
%pr_e%
import org.springframework.data.repository.CrudRepository; import com.pokemon.tcg.api.Models.Type;
public interface TypeRespository extends CrudRepository { }