具有多个控制器的Spring Boot API? [英] Spring Boot API with Multiple Controllers?

查看:112
本文介绍了具有多个控制器的Spring Boot API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am starting to learn Spring Boot. I am struggling to find an example with multiple RestControllers, which indicates to me that I may be doing something wrong. I am trying a very simple example: The goal is to make calls like the following:

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

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

I can only get localhost:8080/ to display. The other calls return response: This application has no explicit mapping for /error, so you are seeing this as a fallback.

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

推荐答案

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

Apparently Controllers in different packages can't be seen with @springbootApplication notation in the main class. The solution explained here, https://kamwo.me/java-spring-boot-mvc-ontroller-not-called/.

这篇关于具有多个控制器的Spring Boot API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆