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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37370948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:14:35  来源:igfitidea点击:

Spring Boot API with Multiple Controllers?

javaspring-mvcmodel-view-controllergradlespring-boot

提问by user1529412

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:

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

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

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.

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

com.demo.departments
Department.java
DepartmentController.java

com.demo.employees
Employee.java
EmployeeController.java

com.demo
BootDemoApplication.java

Code:

代码:

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("[email protected]");

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

采纳答案by user1529412

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/.

显然,在主类中使用 @springbootApplication 符号无法看到不同包中的控制器。此处解释了解决方案,https://kamwo.me/java-spring-boot-mvc-ontroller-not- called/

回答by Apollo

Try below:-

试试下面:-

@ComponentScan
@Configuration
@EnableAutoConfiguration
public class BootDemoApplication {

public static void main(String[] args) {

    SpringApplication.run(BootDemoApplication.class);
}
}

@RestController
@RequestMapping(value = "test", produces =    MediaType.APPLICATION_JSON_VALUE)
public class TestController {

@RequestMapping(method = RequestMethod.GET)
public String test() {
    return "from test method";
}

}

回答by Ian Riley

For Spring-boot 1.3.x and up, passing a base package to SpringBootApplication should work:

对于 Spring-boot 1.3.x 及更高版本,将基本包传递给 SpringBootApplication 应该可以工作:

@SpringBootApplication(scanBasePackages = {"com.demo"})
public class DemoBootApplication {
    // code
}

This worked for me on a similar application using spring-boot 1.4.0. For earlier versions of spring-boot, it appears you'll have forego using SpringBootApplication and instead use the following to get same effect as above:

这对我使用 spring-boot 1.4.0 的类似应用程序有效。对于较早版本的 spring-boot,您似乎已经放弃使用 SpringBootApplication 而是使用以下内容来获得与上述相同的效果:

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"com.demo"})
public class DemoBootApplication {
    // code
}

I found this in the comments on this blog post.

我在这篇博文的评论中发现了这一点。

回答by Patricio Nicola

Try this

尝试这个

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Main {

    public static void main(String[] args) {

        Object[] sources = new Object[2];
        sources[0] = Controller1.class;
        sources[1] = Controller2.class;
        SpringApplication.run(sources, args);
    }

}

回答by Red Boy

ComponentScan annotation works in most cases.

ComponentScan 注释在大多数情况下都有效。

See below example, you could apply similar.
package com.demo;

见下面的例子,你可以应用类似的。
包com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@ComponentScan(basePackages = {"com.demo"})
@SpringBootApplication
public class DemoApplication {

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

回答by VietDD

I'm trying Spring Boot and got same problem, and just fixed it, I post my solution here because I think it maybe helpful for someone.

我正在尝试 Spring Boot 并遇到了同样的问题,只是修复了它,我在这里发布了我的解决方案,因为我认为它可能对某人有帮助。

First, put application class ( which contain main method) at the root of controllers's package:

首先,将应用程序类(包含 main 方法)放在控制器包的根目录下:

com.example.demo
              |
              +-> controller
              |      |
              |      +--> IndexController.java
              |      +--> LoginController.java
              |
              +-> Application.java
com.example.demo
              |
              +-> controller
              |      |
              |      +--> IndexController.java
              |      +--> LoginController.java
              |
              +-> Application.java

Application.java

应用程序.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

Spring will scan all the components of sub-packages of demopackage

Spring会扫描demo包子包的所有组件

IndexController.java (return index.htmlview)

IndexController.java(返回index.html视图)

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = {""})
public class IndexController {

    @GetMapping(value = {""})
    public ModelAndView index() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }

}

LoginController.java (return login.htmlview)

LoginController.java(返回login.html视图)

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = {"/login"})
public class LoginController {
    @GetMapping(value = {""})
    public ModelAndView login() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("login");
        return modelAndView;
    }
}

And now I can enter Index view : http://localhost:8080/demo/and Login view : http://localhost:8080/demo/login

现在我可以进入索引视图:http://localhost:8080/demo/和登录视图:http://localhost:8080/demo/login

回答by Janac Meena

Make sure that the @SpringBootApplication class is in a package which is a level above all other packages that contain @RestControllers, or in the same package.

确保@SpringBootApplication 类位于一个包中,该包高于包含@RestControllers 的所有其他包,或位于同一包中。

回答by jovanchohan

I'm not sure if this is the right way to do it, but when I changed my 2nd Controllers annotation from @Controller to @RestController it started working.

我不确定这是否是正确的方法,但是当我将第二个控制器注释从 @Controller 更改为 @RestController 时,它开始工作。