简体   繁体   English

Spring 引导:无法在本地主机上访问 REST Controller (404)

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

I am trying to adapt the REST Controller example on the Spring Boot website.我正在尝试改编 Spring Boot 网站上的 REST Controller 示例。 Unfortunately I've got the following error when I am trying to access the localhost:8080/item URL.不幸的是,当我尝试访问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: 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)使用应用程序名称(InventoryApp)访问 URL
  • Put another @RequestMapping("/") at class level of the ItemInventoryController在 ItemInventoryController 的ItemInventoryController级别放置另一个@RequestMapping("/")

As far as I understood, I won't need an application-context when using Spring Boot.据我了解,使用 Spring Boot 时不需要应用程序上下文。 Am I right?我对吗?

What else can I do to access the method via URL?我还能做些什么来通过 URL 访问该方法?

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.controller you need to scan for it explicitly. spring-boot 将扫描com.nice.application下的包中的组件,因此如果您的控制器在com.nice.controller中,则需要显式扫描它。

Adding to MattR's answer:添加到 MattR 的答案:

As stated in here , @SpringBootApplication automatically inserts the needed annotations: @Configuration , @EnableAutoConfiguration , and also @ComponentScan ;如此所述, @SpringBootApplication自动插入所需的注解: @Configuration Configuration、@ @EnableAutoConfiguration以及@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 .但是, @ComponentScan ComponentScan 只会在与应用程序相同的包中查找组件,在本例中是您的com.nice.application ,而您的控制器位于com.nice.controller中。 That's why you get 404 because the App didn't find the controller in the application package.这就是你得到 404 的原因,因为应用程序没有在application包中找到控制器。

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"
}

SpringBoot developers recommend to locate your main application class in a root package above other classes. SpringBoot 开发人员建议将您的主应用程序类定位在其他类之上的根包中。 Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute.使用根包还允许使用 @ComponentScan 注释,而无需指定basePackage属性。 Detailed info But be sure that the custom root package exists. 详细信息但请确保自定义根包存在。

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;包 com.spring.boot.app; - You bootup application(ie Main Method -SpringApplication.run(App.class, args);) - 你启动应用程序(即 Main Method -SpringApplication.run(App.class, args);)

    You Rest Controller in with the same package structure Example : package com.spring.boot.app.rest;您使用相同的包结构示例 Rest Controller :package com.spring.boot.app.rest;

  2. Explicitly define the Controller in the Bootup package.在 Bootup 包中显式定义 Controller。

Method 1 is more cleaner.方法1更干净。

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.如果你从http://start.spring.io/下载了这个项目,那么你的主类就在某个包中。 For example if the package for the main class is: "com.example" then and your controller must be in package: "com.example.controller".例如,如果主类的包是:“com.example”,那么您的控制器必须在包中:“com.example.controller”。 Hope this helps.希望这可以帮助。

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.并更新 Controller、Service 和 Repository 包结构,如下所述。

Example: REST-Controller示例:REST 控制器

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.您需要为 Spring Boot MVC 流程中的所有包遵循正确的包结构。

So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.因此,如果您正确修改项目捆绑包结构,那么您的 Spring Boot 应用程序将正常工作。

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.也许它会帮助某人。

for me, I was adding spring-web instead of the spring-boot-starter-web into my pom.xml对我来说,我在 pom.xml 中添加了 spring-web 而不是 spring-boot-starter-web

when i replace it from spring-web to spring-boot-starter-web, all maping is shown in the console log.当我将它从 spring-web 替换为 spring-boot-starter-web 时,所有映射都显示在控制台日志中。

The controller should be in accessible in the same namespace This is what you have控制器应该可以在同一个命名空间中访问这就是你所拥有的在此处输入图像描述

This is how it should be这是应该的

在此处输入图像描述

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注意:不包括 .controller @ComponentScan(basePackages="com.ymc.backend.controller") 因为我有许多其他组件类,如果我只提供 .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";
    };


}

I found a really great thread for this issue.我为这个问题找到了一个非常棒的线程。

https://coderanch.com/t/735307/frameworks/Spring-boot-Rest-api 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.控制器 api 应该在子目录结构中以自动检测控制器。 Otherwise annotation argument can be used.否则可以使用注释参数。

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

Sometimes spring boot behaves weird.有时弹簧靴的行为很奇怪。 I specified below in application class and it works:我在应用程序类中指定了以下内容,它可以工作:

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

I got the 404 problem, because of Url Case Sensitivity .由于Url Case Sensitivity ,我遇到了 404 问题。

For example @RequestMapping(value = "/api/getEmployeeData",method = RequestMethod.GET) should be accessed using http://www.example.com/api/getEmployeeData .例如@RequestMapping(value = "/api/getEmployeeData",method = RequestMethod.GET)应该使用http://www.example.com/api/getEmployeeData If we are using http://www.example.com/api/getemployeedata , we'll get the 404 error.如果我们使用http://www.example.com/api/getemployeedata ,我们会收到 404 错误。

Note: http://www.example.com is just for reference which i mentioned above.注意: http://www.example.com ://www.example.com 仅供参考,我在上面提到过。 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.但这花了我2个小时。 So I hope it will help someone.所以我希望它会帮助别人。

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

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

It could be that something else is running on port 8080, and you're actually connecting to it by mistake.可能是在端口 8080 上运行了其他东西,而您实际上是错误地连接到它。

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.一定要检查一下,特别是如果您的 docker 正在启动您无法控制的其他服务,并且正在端口转发这些服务。

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. Spring Boot Application 具有特定的包结构,以允许 Spring 上下文在其上下文中扫描和加载各种 bean。

In com.nice.application is where your Main Class is and in com.nice.controller, you have your controller classes.在 com.nice.application 中是您的主类,在 com.nice.controller 中,您有控制器类。

Move your com.nice.controller package into com.nice.application so that Spring can access your beans.将您的 com.nice.controller 包移动到 com.nice.application 中,以便 Spring 可以访问您的 bean。

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") ;另一个解决方案以防万一:在我的情况下,问题是我在类级别(在我的控制器中)有一个@RequestMapping("/xxx") ,而在暴露的服务中我有@PostMapping (value = "/yyyy")@GetMapping (value = "/zzz") ; once I commented the @RequestMapping("/xxx") and managed all at method level, worked like a charm.一旦我评论了@RequestMapping("/xxx")并在方法级别管理所有内容,就像一个魅力。

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 .立即关闭的问题在此线程中得到解决。

@SpringBootApplication @ComponentScan(basePackages = {"com.rest"}) // basePackageClasses = HelloController.class) // use above componnent scan to add packages public class RestfulWebServicesApplication { @SpringBootApplication @ComponentScan(basePackages = {"com.rest"}) // basePackageClasses = HelloController.class) // 使用上面的组件扫描添加包 public class RestfulWebServicesApplication {

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

} }

There may 3 reasons causing for this error:导致此错误的原因可能有 3 个:

1> 1>

check your URL you are requesting is correct检查您请求的 URL 是否正确

2> check if your 2> 检查你的

using MVC then use @Controller else use @RestController使用 MVC 然后使用 @Controller 否则使用 @RestController

3> check 3>检查

whether you have placed Controller package(or Class) outside the root package example: com.example.demo -> is your main package是否将控制器包(或类)放在根包示例之外:com.example.demo -> 是您的主包

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

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

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.我有同样的问题,虽然上面的解决方案本身是正确的,但它们对我不起作用,我找到了另一个可能的原因来解决它——你必须从端口关闭应用程序,然后重新启动你的应用程序,如果做 Maven Update 或 project clean 无法解决它。

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.此命令将找到附加在您的应用程序正在运行的端口上的进程 ID - 如果您在默认端口以外的任何地方使用它,请确保指定端口。

You will get the following output:您将获得以下输出: 在此处输入图像描述

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.您关心的是最后一列中的数字,它是与端口关联的进程 ID,应用程序实例运行在该端口上。

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:如果您将 STS4 用于开发目的,您还可以在控制台的顶部边缘看到 PID,但您必须眯着眼睛看:

在此处输入图像描述

At this point, run the next command to kill the process:此时,运行下一条命令杀死进程:

taskkill /pid 22552 /f

And it results in this:结果是:

在此处输入图像描述

Do remember that there will be a different PID for every time you run the application.请记住,每次运行应用程序时都会有不同的 PID。

And finally, you can run it again, and that should do it.最后,您可以再次运行它,应该就可以了。

More relevant materials: Closing network connections更多相关资料: 关闭网络连接

Programmatically shutting down SpringBoot app以编程方式关闭 SpringBoot 应用程序

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. Springboot 的新手,尝试了上面的所有方法,但最终变得很简单,就像我在浏览器上的 URL 末尾有一个 / 而我唯一的 Get() 方法是空白的,只返回一个字符串。 Hope this'll help someone someday.希望有一天这会对某人有所帮助。

Change the Return type from String to ResponseEntity将返回类型从 String 更改为 ResponseEntity

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

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

You can add inside the POM.您可以在 POM 中添加。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM