小编典典

具有多个控制器的Spring Boot API?

spring-boot

我开始学习Spring
Boot。我正在努力寻找带有多个RestControllers的示例,这向我表明我可能做错了事。我正在尝试一个非常简单的示例:目标是进行如下调用:

localhost:8080/
localhost:8080/employees/bob
localhost:8080/departments

我只能让localhost:8080 /显示。其他调用返回响应:此应用程序没有/ error的显式映射,因此您将其视为后备。

com.demo.departments
Department.java
DepartmentController.java

com.demo.employees
Employee.java
EmployeeController.java

com.demo
BootDemoApplication.java

码:

package com.demo.departments
@RestController
@RequestMapping("/departments")
public class DepartmentController {


@RequestMapping("")
public String get(){
    return "test..";

}

@RequestMapping("/list")
public List<Department> getDepartments(){
    return null;

}

}
--------------------------------------------------------------------
package com.demo.employees
@RestController
@RequestMapping("/employees")
public class EmployeeController {

Employee e =new Employee();

@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
public Employee getEmployeeInJSON(@PathVariable String name) {

 e.setName(name);
 e.setEmail("employee1@genuitec.com");

 return e;

}
}
-----------------------------------------------------------------------

package com.demo
@RestController
@SpringBootApplication

public class BootDemoApplication {

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

@RequestMapping("/")
String home(){
    return "<html> This is the home page for Boot Demo.</html>";
}

阅读 357

收藏
2020-05-30

共1个答案

小编典典

显然,主类中的@springbootApplication表示法看不到不同程序包中的控制器。此处介绍的解决方案https://kamwo.me/java-
spring-boot-mvc-ontroller-not-drawn/。

2020-05-30