Spring Boot应用中的Rest Controller无法识别GET请求

12

我正在尝试使用Spring Boot实现一个简单的MVC演示应用,但在执行应用程序时遇到404错误。uri为http://localhost:8080/,旨在显示名为circle的表中的所有行。

  • Spring Boot:1.3.3.RELEASE
  • Java版本:1.8.0_65
  • 数据库:Apache Derby 10.12.1.1

Maven Java项目结构如下:

Maven Java项目结构

Application.java

package com.nomad.dubbed.app;

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

}

CircleController.java

->

CircleController.java

package com.nomad.dubbed.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.nomad.dubbed.dao.CircleService;
import com.nomad.dubbed.model.Circle;

@RestController
@RequestMapping("/")
public class CircleController {
    @Autowired
    private CircleService circleService;

    @RequestMapping(method=RequestMethod.GET)
    public List<Circle> getAll() {
        return circleService.getAll();
    }

}

CircleRepository.java

package com.nomad.dubbed.dao;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.nomad.dubbed.model.Circle;

@Repository
public interface CircleRepository extends JpaRepository<Circle, Integer> {

}

CircleService.java

package com.nomad.dubbed.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.nomad.dubbed.model.Circle;

@Service
public class CircleService {
    @Autowired
    private CircleRepository circleRepository;

    @Transactional(propagation=Propagation.REQUIRED)
    public List<Circle> getAll(){
        return circleRepository.findAll();
    }

}

Circle.java

package com.nomad.dubbed.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="circle")
public class Circle {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;

    public Circle(int id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

应用程序属性文件

spring.datasource.url=jdbc:derby://localhost:1527/db
spring.datasource.driverClassName=org.apache.derby.jdbc.ClientDriver

logging.level.org.springframework.web:DEBUG
logging.level.org.hibernate:DEBUG

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.nomad.dubbed</groupId>
  <artifactId>spring-boot-mvc</artifactId>
  <version>0.0.1-SNAPSHOT</version>


    <properties>
        <derby-client.version>10.11.1.1</derby-client.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.3.RELEASE</version>
        <relativePath />
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-remote-shell</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.apache.derby</groupId>
            <artifactId>derbyclient</artifactId>
            <version>${derby-client.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>spring-boot-mvc</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

数据库已经启动,数据表circle中有5行:

在这里输入图片描述

默认的uri(/beans,/health..)可以正常使用,但实现的控制器无法识别。在控制台中没有显示此类错误,以下是我发送请求后控制台中打印的日志信息。

2016-05-03 14:17:26.594 DEBUG 659 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/]
2016-05-03 14:17:26.596 DEBUG 659 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /
2016-05-03 14:17:26.596 DEBUG 659 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Did not find handler method for [/]
2016-05-03 14:17:26.597 DEBUG 659 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : Matching patterns for request [/] are [/**]
2016-05-03 14:17:26.597 DEBUG 659 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : URI Template variables for request [/] are {}
2016-05-03 14:17:26.597 DEBUG 659 --- [nio-8080-exec-3] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapping [/] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@6c13019c]]] and 1 interceptor
2016-05-03 14:17:26.597 DEBUG 659 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/] is: -1
2016-05-03 14:17:26.597 DEBUG 659 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-05-03 14:17:26.597 DEBUG 659 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Successfully completed request
2016-05-03 14:17:26.597 DEBUG 659 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2016-05-03 14:17:26.600 DEBUG 659 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2016-05-03 14:17:26.600 DEBUG 659 --- [nio-8080-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)]
2016-05-03 14:17:26.600 DEBUG 659 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Last-Modified value for [/error] is: -1
2016-05-03 14:17:26.601 DEBUG 659 --- [nio-8080-exec-3] o.s.w.s.v.ContentNegotiatingViewResolver : Requested media types are [text/html, text/html;q=0.8] based on Accept header types and producible media types [text/html])
2016-05-03 14:17:26.601 DEBUG 659 --- [nio-8080-exec-3] o.s.w.s.v.ContentNegotiatingViewResolver : Returning [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView@2f5f8d71] based on requested media type 'text/html'
2016-05-03 14:17:26.601 DEBUG 659 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Rendering view [org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$SpelView@2f5f8d71] in DispatcherServlet with name 'dispatcherServlet'
2016-05-03 14:17:26.601 DEBUG 659 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet        : Successfully completed request 

Rest App Browser


你的应用程序路径是什么? - ACV
2
采取更小的步骤。首先让getAll返回“hello”。 - Pete B.
11个回答

27

在Spring Boot中,使用不同的URL作为控制器的路径。"/"将映射到位于META-INF/resources和src/main/resources/static/中的静态资源。

编辑:忘记上述内容,在您的应用程序类中执行以下操作:

Application.java

package com.nomad.dubbed.app;

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

@SpringBootApplication
@ComponentScan("com.nomad.dubbed")
public class Application  {

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

}

你的REST控制器未被Spring Boot组件扫描。根据这篇文档http://docs.spring.io/spring-boot/docs/current/reference/html/,Spring扫描的包是在带有@SpringBootApplication注解的类所在包的下方。你的控制器位于一个平行的包中。


@lume 我把它改成了/circles,但是还是出现了同样的错误。@RequestMapping(value="/circles", method=RequestMethod.GET, produces={"application/json","application/xml"}) @ResponseBody public List<Circle> getAll() { return circleService.getAll(); } - gkc123
2
该怎么办,真奇怪。另一个想法:spring-boot在启动时记录了所有的映射URL。你能发布启动日志信息吗? - Lutz Müller
5
我认为我找到了你的问题:你的Rest控制器没有被Spring Boot组件扫描发现。 根据这篇文档https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html,Spring会扫描带有@SpringBootApplication注解类所在包下面的包。 而你的控制器位于一个平行的包中。 - Lutz Müller
我也这么认为。这只是一个简单的Rest控制器,除非我做错了什么,否则应该被映射。 - gkc123
有没有关于创建存储库 bean 失败的信息?有关使用 Spring Data 和 Spring Boot 的示例,请参见此处: https://spring.io/guides/gs/accessing-data-jpa/。还可以标记我的答案为正确,因为它解决了您最初的问题吗? - Lutz Müller
显示剩余7条评论

12
我们不应该在使用@SpringBootApplication注解时同时使用@ComponentScan,因为这不是正确的做法。@SpringBootApplication是三个注解的组合:@ComponentScan@EnableAutoConfiguration@Configuration
具有@SpringBootApplication注解的主类应该在父/超级包中。
例如- com.spring.learning是一个父包,它的子包是com.spring.learning.controllercom.spring.learning.servicecom.spring.learning.pojo
因此它会扫描它的包和子包。
这是最好的实践- 项目布局或结构是Spring Boot中重要的概念。

这是一个正确的答案,但不幸的是它的表述方式无法吸引读者的注意力。也许可以将您的答案加粗,Application移动到com.nomad.dubbed包中,然后在下面详细解释。 - runderworld
你的回答真的很有道理。我也遇到了同样的问题。一旦阅读了你的答案并通过更改包来应用它,它就可以正常工作了。确保控制器包应该在基础包下面。 - Muhammad Bilal

5

这是后台发生的事情。

@SpringBootApplication注释是@Configuration@EnableAutoConfiguration@ComponentScan的组合。

没有参数的@ComponentScan告诉框架在同一包及其子包中查找组件/bean。

您的使用@SpringBootApplication注释的Application类位于com.nomad.dubbed.app包中。因此,它会扫描该包及其下级子包(例如com.nomad.dubbed.app.*)。但是您的CircleController位于com.nomad.dubbed.controller包中,这不是默认情况下扫描的。您的存储库也位于默认扫描包之外,因此它们也不会被Spring框架发现。

那么现在该怎么办呢?有两个选项。

选项1

Application类移动到顶层目录(包)中。在您的情况下为com.nomad.dubbed包。然后,由于所有控制器和其他存储库都在子包中,它们将被框架发现。

选项2

在您的Application类中,使用带有basePackages参数的@ComponentScan注释,以及@SpringBootApplication,如下所示。

@SpringBootApplication
@ComponentScan(basePackages="com.nomad.dubbed")
public class Application  {

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

2
请检查控制器类是否在子包中。
例如,如果主类位于com.myapp包中,则控制器类可以位于同一包中或位于子包(如com.myapp.controllers)中。Spring框架将扫描根包及其所有子包。在这种情况下,一切都将正常工作,您无需使用@ComponentScan。
如果您将主类放置在com.myapp中,并且您希望自动装配其他bean/controller的位置位于com.beans等不是com.myapp的子包中,则会出现找不到bean的问题。
谢谢! Bageeradha

1

问题是Spring Boot扫描包含主方法文件的包。

在我的情况下:demo.example包。因此,控制器应该仅在此包内创建以便进行扫描。 enter image description here

当主文件位于com.example.demo包中时,它无法识别StudentController。


0

实际上,Spring Boot 会扫描在你的核心包下的所有组件,例如:

package com.nomad.dubbed.app;

如果你将控制器、服务和 DAO 包添加到 com.nomad.dubbed.app.controllers、com.nomad.dubbed.app.services 和 com.nomad.dubbed.app.dao 下面,则可以轻松运行 REST 控制器。但是,如果你将所有包与你的 Spring Boot 核心包并列,例如 com.nomad.dubbed.controllers、com.nomad.dubbed.services。

那么你需要扫描 @ComponentScan({"com.nomad.dubbed.controllers","com.nomad.dubbed.services"})。

如果你选择使用 componentscan,那么你还需要扫描 Spring Boot 应用程序包。

因此,最好的方法是将所有包创建在 Spring Boot 应用程序 dubbed.app.xyz 下面...


0
在我看来,这个可见性问题是由于我们将组件扫描交给了Spring,它使用标准约定的方式查找类。在这种情况下,由于Starter类(Application)位于com.nomad.dubbed.app包中,将Controller放在下一级目录下可以帮助Spring使用默认的组件扫描机制查找类。将CircleController放在com.nomad.dubbed.app.controller下应该可以解决这个问题。

0

我曾经遇到过类似的问题。在应用程序类上添加注释@SpringBootApplication(scanBasePackages={"com.nomad.dubbed"})对我有用。


0
我曾经遇到过同样的问题,后来我在应用程序类中添加了@ComponentScan(basePackages = "package.name")。之后我的REST控制器就被识别了。
包名为:

com.nomad.dubbed.app;

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

@SpringBootApplication
@ComponentScan(basePackages = "com.spring.basepkg")
public class Application  {

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

}

0

你可以尝试添加@ResponseBody注解吗?

@RequestMapping(method=RequestMethod.GET)
@ResponseBody
    public List<Circle> getAll() {
        return circleService.getAll();
    }

我按照你的建议修改了代码,但是没有成功。我仍然收到“未找到[/]处理程序方法”的错误提示。@ACV应用程序路径为/ @RequestMapping(value =“ /”,method = RequestMethod.GET,produces = {“application / json”,“application / xml”}) @ResponseBody public List <Circle> getAll(){ return circleService.getAll(); } - gkc123
作为建议,尝试采取较小的步骤。返回字符串列表是否可行? - jstuartmilne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接