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

发布于 2025-01-10 14:04:09 字数 11180 浏览 0 评论 0原文

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

{
  "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:

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

}

我正在使用 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

到目前为止我尝试过的操作:

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

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

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

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/item URL.

{
  "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:

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).

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

烟织青萝梦 2025-01-17 14:04:09

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

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

spring-boot 将扫描 com.nice.application 下面的包中的组件,因此,如果您的控制器位于 com.nice.controller 中,您需要明确扫描它。

Try adding the following to your InventoryApp class

@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.controller you need to scan for it explicitly.

ㄖ落Θ余辉 2025-01-17 14:04:09

添加到 MattR 的答案:

此处所述,@SpringBootApplication会自动插入所需的注解:@Configuration@EnableAutoConfiguration 以及@ComponentScan;但是,@ComponentScan 只会查找与应用程序位于同一包中的组件,在本例中为您的 com.nice.application,而您的控制器位于 com.nice.controller。这就是为什么您会收到 404 错误,因为应用程序在 application 包中找不到控制器。

Adding to MattR's answer:

As stated in here, @SpringBootApplication automatically inserts the needed annotations: @Configuration, @EnableAutoConfiguration, and also @ComponentScan; however, the @ComponentScan will 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 application package.

翻身的咸鱼 2025-01-17 14:04:09

使用以下代码

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

}

响应执行服务后,我得到了相同的 404 响应:

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

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

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

}

响应:

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

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

@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"
}
人│生佛魔见 2025-01-17 14:04:09

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

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

    示例:

    包com.spring.boot.app; - 启动应用程序(即主方法 -SpringApplication.run(App.class, args);)

    您使用相同的包结构来休息控制器
    例子 :
    package com.spring.boot.app.rest;

  2. 在 Bootup 包中显式定义控制器。

方法1更干净。

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.

Method 1 is more cleaner.

朦胧时间 2025-01-17 14:04:09

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

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 basePackage attribute. Detailed info
But be sure that the custom root package exists.

站稳脚跟 2025-01-17 14:04:09

控制器应该可以在同一命名空间中访问
这就是你所拥有的
输入图像描述这里

应该是这样,查看命名空间的层次结构

在此处输入图像描述

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

独守阴晴ぅ圆缺 2025-01-17 14:04:09

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

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.

你列表最软的妹 2025-01-17 14:04:09

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

@SpringBootApplication

@EnableAutoConfiguration

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

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

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

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

例子:
REST-Controller

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

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

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

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

@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

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

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

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

揽清风入怀 2025-01-17 14:04:09

Springboot 新手,尝试了上面的所有内容,但最终就像我在浏览器上的 URL 末尾有一个 / 一样简单,而我唯一的 Get() 方法是空白的,只返回一个字符串。
希望有一天这会对某人有所帮助。

New to Springboot, tried everything above, but ended up being as simple as I had a / at the end of the URL on my browser while my only Get() method was blank, just returning a string.
Hope this'll help someone someday.

浅忆流年 2025-01-17 14:04:09

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

也许它会对某人有所帮助。

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

Maybe it will help somebody.

戏剧牡丹亭 2025-01-17 14:04:09

对我来说,

当我将 spring-web 替换为 spring-boot-starter-web 时,我将 spring-web 而不是 spring-boot-starter-web 添加到我的 pom.xml 中,所有映射都显示在控制台日志中。

for me, I was adding spring-web instead of the spring-boot-starter-web into my pom.xml

when i replace it from spring-web to spring-boot-starter-web, all maping is shown in the console log.

一梦等七年七年为一梦 2025-01-17 14:04:09

我发现了一个非常适合这个问题的主题。

https://coderanch.com/t/735307/frameworks/Spring- boot-Rest-api

控制器api应该位于子目录结构中,以自动检测控制器。否则可以使用注释参数。

@SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.Controller"})

I found a really great thread for this issue.

https://coderanch.com/t/735307/frameworks/Spring-boot-Rest-api

The controller api should be in the sub directory structure to automatically detect the controllers. Otherwise annotation argument can be used.

@SpringBootApplication(scanBasePackages = {"com.example.demo", "com.example.Controller"})
鹤仙姿 2025-01-17 14:04:09

我认为还值得注意的是,项目的绝对路径很重要(在我的例子中,它位于 Windows 计算机上)。我遇到了类似的问题,我重组了我的项目,确保在必要时有 @Controller@RestController 。我确保我正确命名了我的路径,但不知怎的,我总是得到一个白色标签错误页面,当我退后一步时,我意识到我有空格和特殊字符我的项目绝对路径中的某个点,因此我将同一个项目移动到一个新目录,其中文件夹名称中的任何点都没有空格和/或特殊字符并且它有效。

I think it's also worth noting that the absolute path of your project matters (in my case it was on a Windows Computer). I had a similar issue, I restructured my project, made sure I had @Controller or @RestController where necessary. I made sure I named my path correctly but somehow I always ended up with a White Label Error Page and when I took a step back I realized I had spaces and special characters at some point in my project's absolute path, hence I moved the same project to a new directory where there is no space and/or special characters at any point in my folders name and it worked.

忆伤 2025-01-17 14:04:09

我有完全相同的错误,我没有提供基础包。给出正确的基础包,解决了它。

package com.ymc.backend.ymcbe;

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

@SpringBootApplication
@ComponentScan(basePackages="com.ymc.backend")
public class YmcbeApplication {

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

}

注意:不包括.controller
@ComponentScan(basePackages="com.ymc.backend.controller") 因为我
如果我有许多其他组件类,我的项目不会扫描这些组件类
只需给.controller

这是我的控制器示例:

package com.ymc.backend.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@CrossOrigin
@RequestMapping(value = "/user")
public class UserController {

    @PostMapping("/sendOTP")
    public String sendOTP() {
        return "OTP sent";
    };


}

I had exact same error, I was not giving base package. Giving correct base package,ressolved it.

package com.ymc.backend.ymcbe;

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

@SpringBootApplication
@ComponentScan(basePackages="com.ymc.backend")
public class YmcbeApplication {

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

}

Note: not including .controller
@ComponentScan(basePackages="com.ymc.backend.controller") because i
have many other component classes which my project does not scan if i
just give .controller

Here is my controller sample:

package com.ymc.backend.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
@CrossOrigin
@RequestMapping(value = "/user")
public class UserController {

    @PostMapping("/sendOTP")
    public String sendOTP() {
        return "OTP sent";
    };


}
半城柳色半声笛 2025-01-17 14:04:09

有时 Spring Boot 的行为很奇怪。我在应用程序类中指定如下并且它有效:

@ComponentScan("com.seic.deliveryautomation.controller")

Sometimes spring boot behaves weird. I specified below in application class and it works:

@ComponentScan("com.seic.deliveryautomation.controller")
幽蝶幻影 2025-01-17 14:04:09

由于网址区分大小写,我遇到了 404 问题。

例如
@RequestMapping(value = "/api/getEmployeeData",method = RequestMethod.GET) 应使用 http://www.example.com/api/getEmployeeData 访问。如果我们使用 http://www.example.com/api/getemployeedata,我们会收到 404 错误。

笔记:
http://www.example.com 只是我上面提到的参考。它应该是您托管应用程序的域名。

经过一番努力并应用本文中的所有其他答案后,我发现问题仅在于该网址。这可能是一个愚蠢的问题。但这花了我2个小时。所以我希望它能帮助别人。

I got the 404 problem, because of Url Case Sensitivity.

For example
@RequestMapping(value = "/api/getEmployeeData",method = RequestMethod.GET) should be accessed using http://www.example.com/api/getEmployeeData. If we are using http://www.example.com/api/getemployeedata, we'll get the 404 error.

Note:
http://www.example.com is just for reference which i mentioned above. It should be your domain name where you hosted your application.

After a lot of struggle and apply all the other answers in this post, I got that the problem is with that url only. It might be silly problem. But it cost my 2 hours. So I hope it will help someone.

不再见 2025-01-17 14:04:09

如果我们按如下方式使用它也可以工作:

@SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })

It also works if we use as follows:

@SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })
慕烟庭风 2025-01-17 14:04:09

可能是其他程序正在端口 8080 上运行,而您实际上错误地连接到了它。

一定要检查一下,特别是如果您有码头工人正在启动您无法控制的其他服务,并且正在端口转发这些服务。

It could be that something else is running on port 8080, and you're actually connecting to it by mistake.

Definitely check that out, especially if you have dockers that are bringing up other services you don't control, and are port forwarding those services.

葬花如无物 2025-01-17 14:04:09

问题出在你的包结构上。 Spring Boot应用程序有一个特定的包结构,允许spring上下文扫描并加载其上下文中的各种bean。

在 com.nice.application 中是您的主类所在的位置,在 com.nice.controller 中是您的控制器类。

将 com.nice.controller 包移至 com.nice.application 中,以便 Spring 可以访问您的 bean。

The problem is with your package structure. Spring Boot Application has a specific package structure to allow spring context to scan and load various beans in its context.

In com.nice.application is where your Main Class is and in com.nice.controller, you have your controller classes.

Move your com.nice.controller package into com.nice.application so that Spring can access your beans.

燃情 2025-01-17 14:04:09

另一个解决方案,以防有帮助:就我而言,问题是我在类级别(在我的控制器中)有一个 @RequestMapping("/xxx") ,并且在公开的服务中我有 <代码>@PostMapping (value = "/yyyy") 和@GetMapping (value = "/zzz");一旦我评论了 @RequestMapping("/xxx") 并在方法级别管理了所有内容,就像魅力一样。

Another solution in case it helps: in my case, the problem was that I had a @RequestMapping("/xxx") at class level (in my controller), and in the exposed services I had @PostMapping (value = "/yyyy") and @GetMapping (value = "/zzz"); once I commented the @RequestMapping("/xxx") and managed all at method level, worked like a charm.

不及他 2025-01-17 14:04:09

对我来说,问题是我设置的应用程序总是在启动后立即关闭。因此,当我尝试是否可以访问控制器时,应用程序已不再运行。
立即关闭的问题在 此中解决线程

For me, the problem was that I had set up the Application in a way that it always immediately shut down after starting. So by the time I tried out if I could access the controller, the Application wasn't running anymore.
The problem with immediately shutting down is adressed in this thread.

謸气贵蔟 2025-01-17 14:04:09

@SpringBootApplication
@ComponentScan(basePackages = {"com.rest"}) // basePackageClasses = HelloController.class)
// 使用上面的组件扫描来添加包
公共类 RestfulWebServicesApplication {

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

}

@SpringBootApplication
@ComponentScan(basePackages = {"com.rest"}) // basePackageClasses = HelloController.class)
// use above componnent scan to add packages
public class RestfulWebServicesApplication {

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

}

乜一 2025-01-17 14:04:09

可能有3个原因导致此错误:

1>

检查您请求的网址是否正确

2>检查你的

使用MVC,然后使用@Controller,否则使用@RestController

3>查看

您是否将控制器包(或类)放置在根目录之外
包示例:com.example.demo ->是你的主要

将控制器包放入 com.example.demo.controller

There may 3 reasons causing for this error:

1>

check your URL you are requesting is correct

2> check if your

using MVC then use @Controller else use @RestController

3> check

whether you have placed Controller package(or Class) outside the root
package example: com.example.demo -> is your main
package

place controller package inside com.example.demo.controller

星星的軌跡 2025-01-17 14:04:09

我遇到了同样的问题,因为我创建了一个用 @Configuration 注释的内部类,并且它以某种方式禁止组件扫描。

I had the same issue, because I created an inner class annotated with @Configuration and it prohibited somehow the component scan.

你好,陌生人 2025-01-17 14:04:09

我遇到了同样的问题,虽然上述解决方案本身是正确的,但它们对我不起作用,我发现了另一个可能的原因来解决它 - 你必须从端口关闭应用程序,然后重新启动你的应用程序,如果执行 Maven 更新或项目清理未能解决该问题。

简而言之,打开命令提示符,然后运行以下两个命令:

netstat -ano | findstr :8080

此命令将找到附加在您的应用程序运行的端口上的进程 ID - 如果您在除默认。

您将得到以下输出:
输入图片这里的描述

您关心的是最后一列中的数字,它是与运行应用程序实例的端口关联的进程 ID。

如果您使用 STS4 进行开发,您还可以在控制台的顶部边缘看到 PID,但您必须眯着眼睛才能找到它:

在此处输入图像描述"> 此时,运行下一个命令杀死过程:

taskkill /pid 22552 /f

结果如下:

在此处输入图像描述

请记住,每次运行应用程序时都会有不同的 PID。

最后,您可以再次运行它,这样就可以了。

更多相关资料:
关闭网络连接

以编程方式关闭 SpringBoot 应用

I had the same problem, and while the above solution are correct in their own right, they did not work for me, and I found another possible reason that solved it - you have to shut down the application from the port, and restart your application, if doing a Maven Update or a project clean fail to solve it.

Briefly, open a command prompt, and run the following two commands:

netstat -ano | findstr :8080

This command will locate the Process ID that is attached at the port that your app is running on - please make sure to specify the port, if you have it anywhere other than the default.

You will get the following output:
enter image description here

What you care about is the number in the last column, which is the process ID associated with the port, on which the instance of the app is running.

If you are using STS4 for your development purposes, you can also see the PID on the top margin of the console, but you do have to squint for it:

enter image description here

At this point, run the next command to kill the process:

taskkill /pid 22552 /f

And it results in this:

enter image description here

Do remember that there will be a different PID for every time you run the application.

And finally, you can run it again, and that should do it.

More relevant materials:
Closing network connections

Programmatically shutting down SpringBoot app

甜中书 2025-01-17 14:04:09

就我而言,主应用程序类位于根包中,仍然收到白标签错误页面,未找到 404,首先 设置记录所有路由,查看 url 是否正确,然后在 eclipse 运行配置 中检查 spring boot 启用调试输出< /代码>,它会记录详细的servlet转发过程,错误日志是

View name 'discuss', model 
Forwarding to [discuss]
"FORWARD" dispatch for GET "/discuss", parameters={}
Resource not found

discuss.html正确放置在main\resources\templates中,尝试了几分钟,发现html正在使用< code>thymeleaf 但 pom.xml 没有依赖项,添加 thymeleaf 依赖项后已修复。

In my case, main application class is in root package, still getting White Label Error Page with 404 not found, first set log all route, see url correct, then in eclipse Run Configurations check spring boot Enable debug output, it'll log detail servlet forward process, the error log is

View name 'discuss', model 
Forwarding to [discuss]
"FORWARD" dispatch for GET "/discuss", parameters={}
Resource not found

the discuss.html is correctly placed in main\resources\templates, trying for minutes, find html is using thymeleaf but pom.xml no dependency, after add thymeleaf dependency fixed.

桜花祭 2025-01-17 14:04:09

将返回类型从 String 更改为 ResponseEntity

Like : 
@RequestMapping( "/item" )
public ResponseEntity<String> getStockItem() {
        return new ResponseEntity<String>("It's working...!", HttpStatus.OK);
}

Change the Return type from String to ResponseEntity

Like : 
@RequestMapping( "/item" )
public ResponseEntity<String> getStockItem() {
        return new ResponseEntity<String>("It's working...!", HttpStatus.OK);
}
爱格式化 2025-01-17 14:04:09

将您的 springboot 应用程序类放在根包中,例如,如果您的服务、控制器位于 springBoot.xyz 包中,那么您的主类应该位于 springBoot 包中,否则它将不会扫描以下包

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

故事灯 2025-01-17 14:04:09

可以在POM里面添加。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>XXXXXXXXX</version>
</dependency>

You can add inside the POM.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <version>XXXXXXXXX</version>
</dependency>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文