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

时间:2018-05-03 11:09:53

标签: 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);
    }
}

这是我的主要课程

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

我在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>

编辑我的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)

2 个答案:

答案 0 :(得分:3)

有时是因为您的软件包结构。始终确保您的控制器与 @SpringBootApplication 类处于同一 package sub-package 级别。

例如:

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

答案 1 :(得分:2)

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

请参阅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.

请确保:

  • 您在MovieService
  • 包中有一个班级services
  • 该类使用@Service注释
  • 进行注释

更新2

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

@ComponentScan 

通过

@ComponentScan({"com.example.services", "com.example.controllers"})

LearnSpringApplication课程中。

包括所有其他包含使用@Component@Service@Controller@RestController@Repository注释的类的包。

请注意,这是一种解决方法。通常情况下,单独@ComponentScan就足够了 - 或者在评论中提到的@DarrenForsy,即使@SpringBootApplication只适用于您的情况。