Как получить хранилище из пружинного контроллера JHipster? - PullRequest
0 голосов
/ 27 апреля 2020

У меня есть приложение микросервиса JHipster, и я добавил пружинный контроллер. Тем не менее, он создается без хранилища, и я не знаю, как получить его для выполнения задач с данными.

Это код:

@RestController
@RequestMapping("/api/data")
public class DataResource {

    private final Logger log = LoggerFactory.getLogger(DataResource.class);
    private final DeviceRepository deviceRepository;

    public DataResource() {
    }

    /**
    * GET global
    */
    @GetMapping("/global")
    public ResponseEntity<GlobalStatusDTO[]> global() {

        List<Device> list=deviceRepository.findAll();
        GlobalStatusDTO data[]=new GlobalStatusDTO[]{new GlobalStatusDTO(list.size(),1,1,1,1)};
        return ResponseEntity.ok(data);
    }

}

РЕДАКТИРОВАТЬ: мне нужно ввести уже существующее хранилище, вот часть CRUD, где хранилище инициализировано:

@RestController
@RequestMapping("/api")
@Transactional
public class DeviceResource {

    private final Logger log = LoggerFactory.getLogger(DeviceResource.class);

    private static final String ENTITY_NAME = "powerbackDevice";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final DeviceRepository deviceRepository;

    public DeviceResource(DeviceRepository deviceRepository) {
        this.deviceRepository = deviceRepository;
    }

    /**
     * {@code POST  /devices} : Create a new device.
     *
     * @param device the device to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new device, or with status {@code 400 (Bad Request)} if the device has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("/devices")
    public ResponseEntity<Device> createDevice(@Valid @RequestBody Device device) throws URISyntaxException {
...

1 Ответ

2 голосов
/ 27 апреля 2020

Я мог бы вас неправильно понять, но ваша первая часть кода не работает, потому что вы не внедрили DeviceRepository конструктором. Конечно, есть и другие способы инъекций.

@RestController
@RequestMapping("/api/data")
public class DataResource {

    private final Logger log = LoggerFactory.getLogger(DataResource.class);
    private final DeviceRepository deviceRepository;

    //changes are here only, constructor method of injection
    public DataResource(DeviceRepository deviceRepository) {
      this.deviceRepository = deviceRepository; 
    }

    /**
    * GET global
    */
    @GetMapping("/global")
    public ResponseEntity<GlobalStatusDTO[]> global() {

        List<Device> list=deviceRepository.findAll();
        GlobalStatusDTO data[]=new GlobalStatusDTO[]{new GlobalStatusDTO(list.size(),1,1,1,1)};
        return ResponseEntity.ok(data);
    }

}
...