请求映射; java Spring

RequestMapping ; java Spring

我想使用 java spring restful 网络服务制作简单的网络服务。 我在控制器 class 中使用请求映射注释,但是当我 运行 项目时那里没有映射。 这是控制器 Class :

import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import guru.webservice.domain.Customer;
import guru.webservice.services.CustomerService;

@RestController
@RequestMapping(CustomerController.BASE_URL)
public class CustomerController {
    public static final String BASE_URL = "api/v1/customers";
    private final CustomerService customerService;

    public CustomerController(CustomerService customerService) {
        this.customerService = customerService;
    }

    @GetMapping
    List<Customer> getAllCustomers() {
        return customerService.findAllCustomer();
    }

    @GetMapping("/{id}")
    public Customer getCustomerById(@PathVariable Long id) {
        return customerService.findCustomerById(id);
    }
}

要让 Spring 扫描和配置带注释的 @Controller 类,您需要在存储控制器的包上配置组件扫描。

即:/src/main/java/guru/webservices/spring/config/AppConfig.java

AppConfig.java:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc //THIS
@ComponentScan(basePackages = "guru.services") //THIS
public class AppConfig {

}

另外:

@Autowired
private CustomerService customerService;

然后:

@GetMapping("/{id}")
public ResponseEntity getCustomerById(@PathVariable("id") Long id) {

    Customer customer = customerDAO.get(id);
    if (customer == null) {
        return new ResponseEntity("No Customer found for ID " + id, HttpStatus.NOT_FOUND);
    }

    return new ResponseEntity(customer, HttpStatus.OK);
}