簡體   English   中英

Spring 引導:無法在本地主機上訪問 REST Controller (404)

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

我正在嘗試改編 Spring Boot 網站上的 REST Controller 示例。 不幸的是,當我嘗試訪問localhost:8080/item URL 時出現以下錯誤。

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

聚甲醛:

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

入門應用程序:

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 控制器:

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
  • 在 ItemInventoryController 的ItemInventoryController級別放置另一個@RequestMapping("/")

據我了解,使用 Spring Boot 時不需要應用程序上下文。 我對嗎?

我還能做些什么來通過 URL 訪問該方法?

嘗試將以下內容添加到您的 InventoryApp 類

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

spring-boot 將掃描com.nice.application下的包中的組件,因此如果您的控制器在com.nice.controller中,則需要顯式掃描它。

添加到 MattR 的答案:

如此所述, @SpringBootApplication自動插入所需的注解: @Configuration Configuration、@ @EnableAutoConfiguration以及@ComponentScan 但是, @ComponentScan ComponentScan 只會在與應用程序相同的包中查找組件,在本例中是您的com.nice.application ,而您的控制器位於com.nice.controller中。 這就是你得到 404 的原因,因為應用程序沒有在application包中找到控制器。

使用以下代碼執行服務后,我得到了相同的 404 響應

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

}

回復:

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

SpringBoot 開發人員建議將您的主應用程序類定位在其他類之上的根包中。 使用根包還允許使用 @ComponentScan 注釋,而無需指定basePackage屬性。 詳細信息但請確保自定義根包存在。

有兩種方法可以克服這個

  1. 將啟動應用程序放在包結構的開頭,並將所有控制器放在其中。

    例子 :

    包 com.spring.boot.app; - 你啟動應用程序(即 Main Method -SpringApplication.run(App.class, args);)

    您使用相同的包結構示例 Rest Controller :package com.spring.boot.app.rest;

  2. 在 Bootup 包中顯式定義 Controller。

方法1更干凈。

我遇到了這個問題,您需要做的是修復您的包裹。 如果你從http://start.spring.io/下載了這個項目,那么你的主類就在某個包中。 例如,如果主類的包是:“com.example”,那么您的控制器必須在包中:“com.example.controller”。 希望這可以幫助。

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

@SpringBootApplication

@EnableAutoConfiguration

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

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

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

並更新 Controller、Service 和 Repository 包結構,如下所述。

示例:REST 控制器

package com.nice.controller; --> 必須修改為
package com.nice.application.controller;

您需要為 Spring Boot MVC 流程中的所有包遵循正確的包結構。

因此,如果您正確修改項目捆綁包結構,那么您的 Spring Boot 應用程序將正常工作。

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

也許它會幫助某人。

對我來說,我在 pom.xml 中添加了 spring-web 而不是 spring-boot-starter-web

當我將它從 spring-web 替換為 spring-boot-starter-web 時,所有映射都顯示在控制台日志中。

控制器應該可以在同一個命名空間中訪問這就是你所擁有的在此處輸入圖像描述

這是應該的

在此處輸入圖像描述

我有完全相同的錯誤,我沒有提供基本包。 給出正確的基礎包,解決它。

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


}

我為這個問題找到了一個非常棒的線程。

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

控制器 api 應該在子目錄結構中以自動檢測控制器。 否則可以使用注釋參數。

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

有時彈簧靴的行為很奇怪。 我在應用程序類中指定了以下內容,它可以工作:

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

由於Url Case Sensitivity ,我遇到了 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 ://www.example.com 僅供參考,我在上面提到過。 它應該是您托管應用程序的域名。

經過大量努力並在這篇文章中應用了所有其他答案,我發現問題僅在於該網址。 這可能是個愚蠢的問題。 但這花了我2個小時。 所以我希望它會幫助別人。

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

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

可能是在端口 8080 上運行了其他東西,而您實際上是錯誤地連接到它。

一定要檢查一下,特別是如果您的 docker 正在啟動您無法控制的其他服務,並且正在端口轉發這些服務。

問題出在你的包結構上。 Spring Boot Application 具有特定的包結構,以允許 Spring 上下文在其上下文中掃描和加載各種 bean。

在 com.nice.application 中是您的主類,在 com.nice.controller 中,您有控制器類。

將您的 com.nice.controller 包移動到 com.nice.application 中,以便 Spring 可以訪問您的 bean。

另一個解決方案以防萬一:在我的情況下,問題是我在類級別(在我的控制器中)有一個@RequestMapping("/xxx") ,而在暴露的服務中我有@PostMapping (value = "/yyyy")@GetMapping (value = "/zzz") ; 一旦我評論了@RequestMapping("/xxx")並在方法級別管理所有內容,就像一個魅力。

對我來說,問題在於我設置的應用程序總是在啟動后立即關閉。 因此,當我嘗試是否可以訪問控制器時,應用程序已不再運行。 立即關閉的問題在此線程中得到解決。

@SpringBootApplication @ComponentScan(basePackages = {"com.rest"}) // basePackageClasses = HelloController.class) // 使用上面的組件掃描添加包 public class RestfulWebServicesApplication {

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

}

導致此錯誤的原因可能有 3 個:

1>

檢查您請求的 URL 是否正確

2> 檢查你的

使用 MVC 然后使用 @Controller 否則使用 @RestController

3>檢查

是否將控制器包(或類)放在根包示例之外:com.example.demo -> 是您的主包

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

我遇到了同樣的問題,因為我創建了一個用@Configuration注釋的內部類,它以某種方式禁止了組件掃描。

我有同樣的問題,雖然上面的解決方案本身是正確的,但它們對我不起作用,我找到了另一個可能的原因來解決它——你必須從端口關閉應用程序,然后重新啟動你的應用程序,如果做 Maven Update 或 project clean 無法解決它。

簡而言之,打開命令提示符,然后運行以下兩個命令:

netstat -ano | findstr :8080

此命令將找到附加在您的應用程序正在運行的端口上的進程 ID - 如果您在默認端口以外的任何地方使用它,請確保指定端口。

您將獲得以下輸出: 在此處輸入圖像描述

您關心的是最后一列中的數字,它是與端口關聯的進程 ID,應用程序實例運行在該端口上。

如果您將 STS4 用於開發目的,您還可以在控制台的頂部邊緣看到 PID,但您必須眯着眼睛看:

在此處輸入圖像描述

此時,運行下一條命令殺死進程:

taskkill /pid 22552 /f

結果是:

在此處輸入圖像描述

請記住,每次運行應用程序時都會有不同的 PID。

最后,您可以再次運行它,應該就可以了。

更多相關資料: 關閉網絡連接

以編程方式關閉 SpringBoot 應用程序

Springboot 的新手,嘗試了上面的所有方法,但最終變得很簡單,就像我在瀏覽器上的 URL 末尾有一個 / 而我唯一的 Get() 方法是空白的,只返回一個字符串。 希望有一天這會對某人有所幫助。

將返回類型從 String 更改為 ResponseEntity

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

將你的 springbootapplication 類放在根包中,例如,如果你的服務,控制器在 springBoot.xyz 包中,那么你的主類應該在 springBoot 包中,否則它不會掃描下面的包

您可以在 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