Multiple RestController не вызывается из Spring Boot Application - PullRequest
0 голосов
/ 03 марта 2019

Я пытаюсь собрать Spring Boot Rest Application, используя два разных Rest Controller.Я вижу, что вызывается DestinationController, а CustomerController - нет.

Нужна ваша помощь, чтобы разобраться с этим.

Структура пакета enter image description here

Пожалуйста, найдите код RestController

Код адресата получателя:

package com.ayan.tourismSystem.controller.rest;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ayan.tourismSystem.entity.Destination;
import com.ayan.tourismSystem.entity.wrapper.DestinationWrapper;
import com.ayan.tourismSystem.service.DestinationService;

@RestController
@RequestMapping(value="/api/destination")
public class DestinationController {

    private static final Logger logger = LoggerFactory.getLogger(DestinationController.class);

    @Autowired
    private DestinationService destinationService;

    /**
     * @author Ayan Bhattacharyya
     * @param region
     * @return Destination List by region
     */
    @RequestMapping(method= RequestMethod.GET, value="/region/{region}")
    public List<Destination> getDestinationByRegion(
            @PathVariable(value="region")String region){
        return this.destinationService.getDestinationByRegion(region);
    }

    /**
     * @author Ayan Bhattacharyya
     * @param country
     * @return Destination List by country
     */
    @RequestMapping(method= RequestMethod.GET, value="/country/{country}")
    public List<Destination> getDestinationByCountry(
            @PathVariable(value="country")String country){
        return this.destinationService.getDestinationByCountry(country);
    }

    /**
     * @author Ayan Bhattacharyya 
     * @param destinationDetails(Destination Name, Destination Country, Destination Region)
     * @return Destination Id (Created)
     */
    @RequestMapping(method = RequestMethod.POST, value = "/addDestination")
    public Long addDestination(@RequestBody DestinationWrapper addDestination) {
        logger.info("Add destination Service Call Started");
        if (addDestination != null) {
            String name = addDestination.getDestination().getDestinationName();
            String country = addDestination.getDestination().getCountry();
            String region = addDestination.getDestination().getRegion();

            logger.info("Values before passing to service " + name + " " + country + " " + region);
            Destination addedDestination = this.destinationService.addDestination(name, country, region);

            Long response = addedDestination.getDestinationId();

            return response;
        }
        return null;
    }

    @RequestMapping(method = RequestMethod.PUT, value = "/updateDestination")
    public Long updateDestination(@RequestBody DestinationWrapper addDestination) {
        logger.info("Update Destination Call Started");
        if (addDestination != null) {
            Long destinationId = addDestination.getDestination().getDestinationId();
            String name = addDestination.getDestination().getDestinationName();
            String country = addDestination.getDestination().getCountry();
            String region = addDestination.getDestination().getRegion();

            logger.info("Values before passing to service " + destinationId + " " + name + " " + country + " " + region);
            Destination addedDestination = this.destinationService.updateDestination(destinationId, name, country, region);

            Long response = addedDestination.getDestinationId();

            return response;
        }
        return null;
    }

    @RequestMapping(method = RequestMethod.DELETE, value = "/deleteDestination/{destinationId}")
    public void deleteDestination(@PathVariable(value="destinationId")String destinationId) {
        logger.info("Delete Destination Call Started");

            logger.info("Values before passing to service " + destinationId);
            Long id = Long.valueOf(destinationId);
            this.destinationService.deleteDestination(id);
    }
}

Код контроллера клиента

package com.ayan.tourismSystem.controller.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.ayan.tourismSystem.entity.Customer;
import com.ayan.tourismSystem.entity.wrapper.CustomerWrapper;
import com.ayan.tourismSystem.service.CustomerService;

@RestController
@RequestMapping(name = "/customer")
public class CustomerController {

    private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    private CustomerService customerService;

    /**
     * @author Ayan Bhattacharyya 
     * @param destinationDetails(Destination Name, Destination Country, Destination Region)
     * @return Destination Id (Created)
     */
    @RequestMapping(method = RequestMethod.POST, value = "/addCustomer")
    public Long addCustomer(@RequestBody CustomerWrapper addCustomer) {
        logger.info("Add Customer Call Started");
        if (addCustomer != null) {
            String firstName = addCustomer.getCustomer().getFirstName();
            String middleName = addCustomer.getCustomer().getMiddleName();
            String lastName = addCustomer.getCustomer().getLastName();
            String email = addCustomer.getCustomer().getEmail();
            String mobile = addCustomer.getCustomer().getMobile();
            String address = addCustomer.getCustomer().getAddress();
            String state = addCustomer.getCustomer().getAddress();
            String country = addCustomer.getCustomer().getCountry();
            String postcode = addCustomer.getCustomer().getPostcode();
            String travelDocumentType = addCustomer.getCustomer().getTravelDocumentType();
            String travelDocumentNumber = addCustomer.getCustomer().getTravelDocumentNumber();

            Customer customer = this.customerService.addCustomer(firstName, middleName, 
                    lastName, email, mobile, address, state, country, 
                    postcode, travelDocumentType, travelDocumentNumber);
            if(customer != null){
                return customer.getCustomerId();
            }
            else{
                return null;
            }
        }

        return null;
    }
}

Код приложения пружины

package com.ayan.tourismSystem;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = {"com.ayan.*"})
public class TourismSystemApplication {

    public static void main(String[] args) {
        SpringApplication.run(TourismSystemApplication.class, args);
    }

}

Пожалуйстаподскажите мне, что я пропускаю / делаю неправильно здесь.

Заранее спасибо!Аян Бхаттачарья

Ответы [ 2 ]

0 голосов
/ 04 марта 2019

Вы используете неверный атрибут в RequestMapping для определения сопоставления URL.

@RequestMapping(name = "/customer")

следует заменить на

@RequestMapping(value = "/customer")

или просто

@RequestMapping("/customer")

Атрибут name просто назначает имя сопоставлению, а value указывает сопоставление URL

.
0 голосов
/ 03 марта 2019

TLDR; Вам не нужно добавлять scanBasePackages, так как Spring будет искать все подпапки в зависимости от местоположения вашего основного класса.

Объяснение:

Компоненты весенней проверки загрузки, начиная с папки, в которой находится класс @SpringBootApplication, и следуя всем подпапкам.

Единственная аннотация @ SpringBootApplication может использоваться для включения этих трех функций, а именно: @ EnableAutoConfiguration, @ComponentScan, @ Configuration .

@ ComponetScan включить @ Component сканирование пакета, в котором находится приложение.

...