java - 请求映射; java Spring

标签 java spring web-services request-mapping

我想使用 java spring Restful Web 服务制作简单的 Web 服务。 我在 Controller 类中使用请求映射注释,但是当我运行项目时,那里没有映射。 这是 Controller 类:

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);
    }
}

heare is out put

最佳答案

为了让Spring扫描并配置@Controller注解的类,你需要在存储 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);
}

关于java - 请求映射; java Spring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53029438/

相关文章:

java - Titan Cassandra 多线程事务锁定

java - 如何使用 spring-social 从 Facebook 获取个人资料图片 url?

java - 如何在 Spring Batch 中使用 StaxEventItemReader 处理复杂的 xml

java - 带有应用程序/八位字节流的spring boot multipartFile抛出异常

java - 由于数据量巨大,AsyncTask 出现异常

c# - Webservice复杂类型和类继承

java - 通过代理服务器调用webservice

java - 从字符串中提取数字

java - 配置基本路径下的 Spring Data REST Controller

spring - 多个场景@RequestMapping 与 Accept 或 ResponseEntity 一起生成 JSON/XML