我想使用 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);
}
}
最佳答案
为了让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/