Java Spring Boot:无法访问本地主机上的 REST 控制器 (404)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31318107/
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 10:54:51  来源:igfitidea点击:

Spring Boot: Cannot access REST Controller on localhost (404)

javarestspring-boot

提问by mchlfchr

I am trying to adapt the REST Controller example on the Spring Boot website. Unfortunately I've got the following error when I am trying to access the localhost:8080/itemURL.

我正在尝试调整 Spring Boot 网站上的 REST 控制器示例。不幸的是,当我尝试访问localhost:8080/itemURL时出现以下错误。

{
  "timestamp": 1436442596410,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/item"
}

POM:

聚甲醛:

<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>SpringBootTest</groupId>
   <artifactId>SpringBootTest</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <properties>
      <javaVersion>1.8</javaVersion>
      <mainClassPackage>com.nice.application</mainClassPackage>
      <mainClass>${mainClassPackage}.InventoryApp</mainClass>
   </properties>

   <build>
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.3</version>
            <configuration>
               <source>${javaVersion}</source>
               <target>${javaVersion}</target>
            </configuration>
         </plugin>

         <!-- Makes the Spring Boot app executable for a jar file. The additional configuration is needed for the cmd: mvn spring-boot:repackage 
            OR mvn spring-boot:run -->
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>

            <configuration>
               <mainClass>${mainClass}</mainClass>
               <layout>ZIP</layout>
            </configuration>
            <executions>
               <execution>
                  <goals>
                     <goal>repackage</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>

         <!-- Create a jar with a manifest -->
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
               <archive>
                  <manifest>
                     <mainClass>${mainClass}</mainClass>
                  </manifest>
               </archive>
            </configuration>
         </plugin>
      </plugins>
   </build>

   <dependencyManagement>
      <dependencies>
         <dependency>
            <!-- Import dependency management from Spring Boot. This replaces the usage of the Spring Boot parent POM file. -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.2.5.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
         </dependency>

         <!-- more comfortable usage of several features when developing in an IDE. Developer tools are automatically disabled when 
            running a fully packaged application. If your application is launched using java -jar or if it's started using a special classloader, 
            then it is considered a 'production application'. Applications that use spring-boot-devtools will automatically restart whenever files 
            on the classpath change. -->
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
         </dependency>
      </dependencies>
   </dependencyManagement>

   <dependencies>
      <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>

      <dependency>
         <groupId>com.google.guava</groupId>
         <artifactId>guava</artifactId>
         <version>15.0</version>
      </dependency>
   </dependencies>
</project>

Starter-Application:

入门级应用:

package com.nice.application;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class InventoryApp {
   public static void main( String[] args ) {
      SpringApplication.run( InventoryApp.class, args );
   }
}

REST-Controller:

REST-控制器:

package com.nice.controller; 
@RestController // shorthand for @Controller and @ResponseBody rolled together
public class ItemInventoryController {
   public ItemInventoryController() {
   }

   @RequestMapping( "/item" )
   public String getStockItem() {
      return "It's working...!";
   }

}

I am building this project with Maven. Started it as jar (spring-boot:run) and as well inside the IDE (Eclipse).

我正在用 Maven 构建这个项目。以 jar (spring-boot:run) 以及 IDE (Eclipse) 的形式启动它。

Console Log:

控制台日志:

2015-07-09 14:21:52.132  INFO 1204 --- [           main] c.b.i.p.s.e.i.a.InventoryApp          : Starting InventoryApp on 101010002016M with PID 1204 (C:\eclipse_workspace\SpringBootTest\target\classes started by MFE in C:\eclipse_workspace\SpringBootTest)
2015-07-09 14:21:52.165  INFO 1204 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7a3d45bd: startup date [Thu Jul 09 14:21:52 CEST 2015]; root of context hierarchy
2015-07-09 14:21:52.661  INFO 1204 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver': replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2015-07-09 14:21:53.430  INFO 1204 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2015-07-09 14:21:53.624  INFO 1204 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2015-07-09 14:21:53.625  INFO 1204 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.0.23
2015-07-09 14:21:53.731  INFO 1204 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2015-07-09 14:21:53.731  INFO 1204 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1569 ms
2015-07-09 14:21:54.281  INFO 1204 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2015-07-09 14:21:54.285  INFO 1204 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2015-07-09 14:21:54.285  INFO 1204 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2015-07-09 14:21:54.508  INFO 1204 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@7a3d45bd: startup date [Thu Jul 09 14:21:52 CEST 2015]; root of context hierarchy
2015-07-09 14:21:54.573  INFO 1204 --- [           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.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2015-07-09 14:21:54.573  INFO 1204 --- [           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.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest)
2015-07-09 14:21:54.594  INFO 1204 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-07-09 14:21:54.594  INFO 1204 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-07-09 14:21:54.633  INFO 1204 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2015-07-09 14:21:54.710  INFO 1204 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2015-07-09 14:21:54.793  INFO 1204 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2015-07-09 14:21:54.795  INFO 1204 --- [           main] c.b.i.p.s.e.i.a.InventoryApp          : Started InventoryApp in 2.885 seconds (JVM running for 3.227)
2015-07-09 14:22:10.911  INFO 1204 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2015-07-09 14:22:10.911  INFO 1204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2015-07-09 14:22:10.926  INFO 1204 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 15 ms

What I've tried so far:

到目前为止我尝试过的:

  • Accessing the URL with the application name (InventoryApp)
  • Put another @RequestMapping("/")at class level of the ItemInventoryController
  • 使用应用程序名称访问 URL (InventoryApp)
  • 将另一个@RequestMapping("/")放在班级级别ItemInventoryController

As far as I understood, I won't need an application-context when using Spring Boot. Am I right?

据我了解,使用 Spring Boot 时我不需要应用程序上下文。我对吗?

What else can I do to access the method via URL?

我还能做什么来通过 URL 访问该方法?

采纳答案by MattR

Try adding the following to your InventoryApp class

尝试将以下内容添加到您的 InventoryApp 类

@SpringBootApplication
@ComponentScan(basePackageClasses = ItemInventoryController.class)
public class InventoryApp {
...

spring-boot will scan for components in packages below com.nice.application, so if your controller is in com.nice.controlleryou need to scan for it explicitly.

spring-boot 将扫描下面包中的组件com.nice.application,所以如果你的控制器在com.nice.controller你需要明确扫描它。

回答by Amit S

Your URL should be, you are missing the application context: localhost:8080/SpringBootTest/item

您的 URL 应该是,您缺少应用程序上下文:localhost:8080/SpringBootTest/item

回答by cipley

Adding to MattR's answer:

As stated in here, @SpringBootApplicationautomatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScanwill only look for the components in the same package as the App, in this case your com.nice.application, whereas your controller resides in com.nice.controller. That's why you get 404 because the App didn't find the controller in the applicationpackage.

添加到将mattr的回答是:

由于在规定位置@SpringBootApplication会自动将所需的注释:@Configuration@EnableAutoConfiguration,和也@ComponentScan; 但是,它@ComponentScan只会查找与应用程序位于同一包中的组件,在这种情况下是您的com.nice.application,而您的控制器位于com.nice.controller. 这就是你得到 404 的原因,因为应用程序没有在application包中找到控制器。

回答by Mohammed Sarfaraz

There are 2 method to overcome this

有两种方法可以克服这个问题

  1. Place the bootup application at start of the package structure and rest all controller inside it.

    Example :

    package com.spring.boot.app; - You bootup application(i.e. Main Method -SpringApplication.run(App.class, args);)

    You Rest Controller in with the same package structure Example : package com.spring.boot.app.rest;

  2. Explicitly define the Controller in the Bootup package.

  1. 将启动应用程序放在包结构的开头,并将所有控制器放在其中。

    例子 :

    包 com.spring.boot.app; - 你启动应用程序(即 Main Method -SpringApplication.run(App.class, args);)

    您使用相同的包结构将 Controller 放入 Rest Controller 示例:package com.spring.boot.app.rest;

  2. 在 Bootup 包中显式定义 Controller。

Method 1 is more cleaner.

方法1更干净。

回答by f.trajkovski

I had this issue and what you need to do is fix your packages. If you downloaded this project from http://start.spring.io/then you have your main class in some package. For example if the package for the main class is: "com.example" then and your controller must be in package: "com.example.controller". Hope this helps.

我遇到了这个问题,您需要做的是修复您的软件包。如果你从http://start.spring.io/下载了这个项目,那么你的主类就在某个包中。例如,如果主类的包是:“com.example”,那么你的控制器必须在包中:“com.example.controller”。希望这可以帮助。

回答by Anjan

You need to modify the Starter-Application class as shown below.

您需要修改 Starter-Application 类,如下所示。

@SpringBootApplication

@EnableAutoConfiguration

@ComponentScan(basePackages="com.nice.application")

@EnableJpaRepositories("com.spring.app.repository")

public class InventoryApp extends SpringBootServletInitializer {..........

And update the Controller, Service and Repository packages structure as I mentioned below.

并更新我在下面提到的控制器、服务和存储库包结构。

Example: REST-Controller

示例:REST 控制器

package com.nice.controller;--> It has to be modified as
package com.nice.application.controller;

package com.nice.controller;--> 必须修改为
package com.nice.application.controller;

You need to follow proper package structure for all packages which are in Spring Boot MVC flow.

您需要为 Spring Boot MVC 流程中的所有包遵循正确的包结构。

So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.

因此,如果您正确修改了项目包包结构,那么您的 Spring Boot 应用程序将正常工作。

回答by torina

SpringBoot developers recommend to locate your main application class in a root package above other classes. Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackageattribute. Detailed infoBut be sure that the custom root package exists.

SpringBoot 开发人员建议将您的主应用程序类放在其他类之上的根包中。使用根包还允许使用 @ComponentScan 注释,而无需指定basePackage属性。 详细信息但请确保自定义根包存在。

回答by Ihor Khomiak

Replace @RequestMapping( "/item" )with @GetMapping(value="/item", produces=MediaType.APPLICATION_JSON_VALUE).

替换@RequestMapping( "/item" )@GetMapping(value="/item", produces=MediaType.APPLICATION_JSON_VALUE)

Maybe it will help somebody.

也许它会帮助某人。

回答by ASG

Place your springbootapplication class in root package for example if your service,controller is in springBoot.xyz package then your main class should be in springBoot package otherwise it will not scan below packages

将你的 springbootapplication 类放在根包中,例如如果你的服务,控制器在 springBoot.xyz 包中,那么你的主类应该在 springBoot 包中,否则它不会扫描下面的包

回答by Mahender Ambala

Same 404 response I got after service executed with the below code

使用以下代码执行服务后得到相同的 404 响应

@Controller
@RequestMapping("/duecreate/v1.0")
public class DueCreateController {

}

Response:

回复:

{
"timestamp": 1529692263422,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/duecreate/v1.0/status"
}

after changing it to below code I received proper response

将其更改为以下代码后,我收到了正确的回复

@RestController
@RequestMapping("/duecreate/v1.0")
public class DueCreateController {

}

Response:

回复:

{
"batchId": "DUE1529673844630",
"batchType": null,
"executionDate": null,
"status": "OPEN"
}