Spring Boot:无法访问localhost上的REST控制器(404)

mch*_*chr 87 java rest spring-boot

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

{
  "timestamp": 1436442596410,
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/item"
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

起动器应用:

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

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

}
Run Code Online (Sandbox Code Playgroud)

我正在用Maven构建这个项目.将其作为jar(spring-boot:run)以及IDE(Eclipse)内部启动.

控制台日志:

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
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试过的:

  • 使用应用程序名称(InventoryApp)访问URL
  • 把另一个@RequestMapping("/")放在班级ItemInventoryController

据我所知,使用Spring Boot时我不需要应用程序上下文.我对吗?

我还可以通过URL访问该方法吗?

Mat*_*ttR 163

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

@SpringBootApplication
@ComponentScan(basePackageClasses = ItemInventoryController.class)
public class InventoryApp {
...
Run Code Online (Sandbox Code Playgroud)

spring-boot将扫描下面的包中的组件com.nice.application,因此如果你的控制器在com.nice.controller你需要显式扫描它.

  • 将应用程序放在"根"包中似乎是最容易的,例如"org.whatever"和子包中的控制器,服务. (6认同)
  • 我有同样的问题,但在找到这个解决方案之前我发现它...更多结束.把你的spring引导应用程序类(在其中定义main方法)一级到控制器包..然后控制器将对此可见并且将工​​作 (6认同)
  • 我也有同样的问题。我尝试使用组件扫描,但什么也没有:-(我的问题:http://stackoverflow.com/questions/33000931/spring-boot-cannot-access-some-controllers (2认同)
  • 请注意`@SpringBootApplication`包含`@Configuration` (2认同)
  • 您还可以使用“@ComponentScan(basePackages = "com.nice.controller")”。组件默认扫描从路径开始,其中是App类,并且还扫描附属包。在这种情况下,您不需要使用 @ComponentScan 注释。它会自动执行。如果您有超过 1 个控制器,也可以将它们放在不同的包中,您可以将它们链接起来。在这种情况下,避免冲突很重要。 (2认同)

cip*_*ley 40

添加到将mattr的回答是:

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

  • 如果从上面的解释中已经不完全清楚,那么带有@SpringBootApplication注释的类必须是ABOVE,或者在目录结构中与您希望它找到的内容处于同一级别.例如,我有com.app.configuration和com.app.controllers.我错误地将我的Application类放入com.app.configuration中,com.app.configuration中的其他所有内容都运行正常,但com.app.controllers中没有任何内容被加载.我将我的Application类移动到com.app中,并找到了其他地方的bean,并开始工作.菜鸟错误对我来说. (4认同)
  • 添加@ComponentScan(basePackages =“ com.base.package”)在我的情况下解决了它 (2认同)

Che*_*nda 14

The controller should be accessible in the same namespace This is what you have enter image description here

This is how it should be, see the hierarchy of the namespace

enter image description here


小智 9

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

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

    例子 :

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

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

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

方法1更干净。

  • spring boot 讨厌应用程序类位于除基本包之外的某个包下。 (2认同)

tor*_*ina 8

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


小智 8

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

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

}
Run Code Online (Sandbox Code Playgroud)

响应:

{
"timestamp": 1529692263422,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/duecreate/v1.0/status"
}
Run Code Online (Sandbox Code Playgroud)

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

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

}
Run Code Online (Sandbox Code Playgroud)

响应:

{
"batchId": "DUE1529673844630",
"batchType": null,
"executionDate": null,
"status": "OPEN"
}
Run Code Online (Sandbox Code Playgroud)

  • 如果其他读者看不到它,`@Controller` -&gt; `@RestController` (5认同)

f.t*_*ski 5

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


小智 5

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

@SpringBootApplication

@EnableAutoConfiguration

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

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

public class InventoryApp extends SpringBootServletInitializer {..........
Run Code Online (Sandbox Code Playgroud)

并更新控制器、服务和存储库包结构,如下所述。

示例:REST 控制器

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

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

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

  • EnableAutoConfiguration包含在@SpringBootApplication中,所以添加它是没有用的。 (4认同)