Spring Boot 控制器为所有 api 端点返回 404

rel*_*der 5 spring spring-boot

我是 Spring 生态系统的新手。我被这种特殊情况困住了。我的应用程序服务器响应404我所有的 API 端点。

这是我的控制器

package com.example.controllers;

import com.example.models.Movie;
import com.example.services.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
public class MovieController {

    @Autowired
    private MovieService movieService;

    @RequestMapping(value = "/movies", method = RequestMethod.GET)
    @ResponseBody
    public List<Movie> getAllMovies(){
        return movieService.getAllMovies();
    }

    @RequestMapping(value = "/movies", method = RequestMethod.POST)
    @ResponseBody
    public Movie addNewMovie(@RequestBody Movie movie){
        System.out.println("Hello World");
        return movieService.addMovie(movie);
    }

    @RequestMapping(value = "/movies/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Optional<Movie> getMovieById(@PathVariable String id){
        return movieService.getMovieById(id);
    }

    @RequestMapping(value = "/movies", method = RequestMethod.PUT)
    @ResponseBody
    public Movie updateMovie(@RequestBody Movie movie){
        return movieService.updateMovie(movie);
    }

    @RequestMapping(value = "/movies/{id}", method = RequestMethod.DELETE)
    public void removeMovieById(@PathVariable String id){
        movieService.deleteMovie(id);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的主要课程

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@EnableAutoConfiguration
@ComponentScan
@SpringBootApplication
public class LearnSpringApplication{
    public static void main(String[] args) {
        SpringApplication.run(LearnSpringApplication.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在 localhost 上运行它,端口是 8080。我在此之前确实设置了一个小应用程序,并且按预期工作。但是,我猜这是因为控制器在不同的包中,因为在以前的应用程序中,主类和控制器在同一个包中。

编辑这是我的pom.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<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.example</groupId>
    <artifactId>learn_spring</artifactId>
    <version>0.0.1</version>
    <packaging>jar</packaging>

    <name>learn_spring</name>
    <description>Project to learn Spring</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>10</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</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-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>
Run Code Online (Sandbox Code Playgroud)

编辑我的 Spring-Boot 启动日志是

2018-05-03 17:16:44.937  INFO 14017 --- [           main] com.example.LearnSpringApplication       : Starting LearnSpringApplication v0.0.1 on tfc with PID 14017 (/home/ayush/Workspace/learn_spring/target/learn_spring-0.0.1.jar started by ayush in /home/ayush/Workspace/learn_spring)
2018-05-03 17:16:44.940  INFO 14017 --- [           main] com.example.LearnSpringApplication       : No active profile set, falling back to default profiles: default
2018-05-03 17:16:45.045  INFO 14017 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6aba2b86: startup date [Thu May 03 17:16:45 IST 2018]; root of context hierarchy
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (jar:file:/home/ayush/Workspace/learn_spring/target/learn_spring-0.0.1.jar!/BOOT-INF/lib/spring-core-5.0.5.RELEASE.jar!/) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
2018-05-03 17:16:46.113  INFO 14017 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2018-05-03 17:16:46.138  INFO 14017 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-05-03 17:16:46.139  INFO 14017 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.29
2018-05-03 17:16:46.151  INFO 14017 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib]
2018-05-03 17:16:46.218  INFO 14017 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-05-03 17:16:46.218  INFO 14017 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1186 ms
2018-05-03 17:16:46.336  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
2018-05-03 17:16:46.339  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-05-03 17:16:46.340  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-05-03 17:16:46.340  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-05-03 17:16:46.340  INFO 14017 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-05-03 17:16:46.455  INFO 14017 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:46.720  INFO 14017 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6aba2b86: startup date [Thu May 03 17:16:45 IST 2018]; root of context hierarchy
2018-05-03 17:16:46.786  INFO 14017 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-05-03 17:16:46.787  INFO 14017 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-05-03 17:16:46.817  INFO 14017 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:46.817  INFO 14017 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-05-03 17:16:47.060  INFO 14017 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2018-05-03 17:16:47.151  INFO 14017 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:12}] to localhost:27017
2018-05-03 17:16:47.155  INFO 14017 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 6, 3]}, minWireVersion=0, maxWireVersion=6, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=null, roundTripTimeNanos=2192957}
2018-05-03 17:16:47.323  INFO 14017 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-05-03 17:16:47.392  INFO 14017 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2018-05-03 17:16:47.395  INFO 14017 --- [           main] com.example.LearnSpringApplication       : Started LearnSpringApplication in 2.89 seconds (JVM running for 3.296)
Run Code Online (Sandbox Code Playgroud)

小智 6

有时是因为你的包结构。始终确保您的控制器与@SpringBootApplication类位于相同的子包级别。

例如:

如果应用程序类位于 com.ab,则控制器应位于 com.ab 或com.abccom.abcd等。您不必总是添加@ComponentScan来注册它们。


Twi*_*wiN 3

您使用的是 IntelliJ IDEA 社区版本,它不支持 Spring 框架:

请参阅https://www.jetbrains.com/idea/features/editions_comparison_matrix.html以供参考

更新

由于您使用的是命令行,因此上述内容不适用。不过,我会把它留在这里作为参考。


在注释中,您指定了在运行mvn clean package后跟时java -jar target/whatever-your-project-name-is.jar,您会收到以下错误:

Field movieService in com.example.controllers.MovieController required a bean of type 'com.example.services.MovieService' that could not be found.
Run Code Online (Sandbox Code Playgroud)

请确保:

  • MovieService你的包中有一个类services
  • 该类用@Service注释进行注释

更新2

由于上述方法不起作用,请尝试更换

@ComponentScan 
Run Code Online (Sandbox Code Playgroud)

经过

@ComponentScan({"com.example.services", "com.example.controllers"})
Run Code Online (Sandbox Code Playgroud)

在你的LearnSpringApplication班级里。

包括所有其他具有用@Component@Service@Controller@RestController或注释的类的包@Repository

请注意,这是一种解决方法。通常,@ComponentScan单独拥有应该足够了——或者正如@DarrenForsythe 在评论中提到的,即使只是@SpringBootApplication对于你的情况来说也应该足够了。

  • 包括所有具有用“@Component”、“@Service”、“@Controller”、“@RestController”或“@Repository”注释的类的包。 (2认同)