스프링 부트: 로컬 호스트의 REST 컨트롤러에 액세스할 수 없음(404)
Spring Boot (스프링 부트) REST (레스트) 아쉽게도 제가 할 때과 같은 localhost:8080/item URL 니니 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>
스타터 응용 프로그램:
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...!";
}
}
저는 이 프로젝트를 메이븐과 함께 만들고 있습니다.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
내가 지금까지 시도한 것:
- 응용 프로그램 이름을 사용하여 URL 액세스(InventoryApp)
- 더 넣으세요.
@RequestMapping("/")ItemInventoryController
Spring Boot을 사용할 때는 어플리케이션 콘텍스트가 필요 없는 것으로 알고 있습니다.내 말이 맞니?
URL을 통해 메서드에 액세스하려면 또 무엇을 해야 합니까?
InventoryApp 클래스에 다음을 추가해 보십시오.
@SpringBootApplication
@ComponentScan(basePackageClasses = ItemInventoryController.class)
public class InventoryApp {
...
는 spring-boot보다 아래 된 컴포넌트를 합니다.com.nice.application가 「」에 com.nice.controller이치노
MattR matt matt :
여기 기재된 바와 같이@SpringBootApplication합니다.@Configuration,@EnableAutoConfiguration및 , 「」도 있습니다.@ComponentScan ,,@ComponentScan과 동일한 .com.nice.application, 는 「」, 「」에 com.nice.controller 404는 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"
}
Spring Boot 개발자는 다른 클래스보다 루트 패키지에서 메인 응용 프로그램클래스를 찾을 것을 권장합니다.루트 패키지를 사용하면 basePackage 속성을 지정하지 않고도 @ComponentScan 주석을 사용할 수 있습니다.상세 정보 단, 커스텀루트 패키지가 존재하는지 확인합니다.
이를 극복하기 위한 두 가지 방법이 있다.
부트업 애플리케이션을 패키지 구조 시작 부분에 배치하고 모든 컨트롤러를 패키지 구조 안에 놓습니다.
예:
package com.spring.boot.app; - 어플리케이션 부팅(즉, 메인 메서드 - Spring Application.run(App.class, args;);)
동일한 패키지 구조의 Rest 컨트롤러 예: package com.spring.boot.app.rest;
부트업 패키지에 컨트롤러를 명시적으로 정의합니다.
방법 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 {..........
또한 컨트롤러, 서비스 및 저장소 패키지 구조를 다음과 같이 업데이트합니다.
예: REST 컨트롤러
package com.nice.controller;.--> > > > > > > > > > > > > > > > > > > > > > 라고.
package com.nice.application.controller;
Spring Boot MVC 플로우에 있는 모든 패키지에 대해 적절한 패키지 구조를 따라야 합니다.
따라서 프로젝트 번들 패키지 구조를 올바르게 수정하면 스프링 부트 앱이 올바르게 작동합니다.
컨트롤러는 같은 네임스페이스에서 액세스할 수 있어야 합니다.이것이 바로 이 네임스페이스입니다.
이렇게 해야 한다
@RequestMapping( "/item" )@GetMapping(value="/item", produces=MediaType.APPLICATION_JSON_VALUE).
그게 누군가에게 도움이 될지도 몰라.
저는 spring-boot-starter-web 대신 spring-web을 pom.xml에 추가했습니다.
spring-web에서 spring-boot-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
컨트롤러를 자동으로 검출하려면 controller 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이치노응용 프로그램을 호스트한 도메인 이름이어야 합니다.
이 투고에 기재되어 있는 다른 모든 답변을 적용하기 위해 많은 노력을 한 결과, 그 URL에만 문제가 있다는 것을 알게 되었습니다.바보 같은 문제일 수도 있어요.하지만 2시간이나 걸렸어요.그래서 누군가에게 도움이 됐으면 좋겠어요.
다음과 같이 사용하는 경우에도 동작합니다.
@SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })
포트 8080에서 다른 무언가가 실행되고 있을 수 있습니다.실제로 포트 8080에 잘못 접속하고 있을 수 있습니다.
특히 제어할 수 없는 다른 서비스를 실행하고 이러한 서비스를 포트 포워딩하는 도커가 있는 경우에는 반드시 확인하십시오.
문제는 패키지 구조에 있습니다.Spring Boot Application에는 특정 패키지 구조가 있어 Spring 컨텍스트에서 다양한 콩을 스캔하여 로드할 수 있습니다.
com.nice.application은 메인 클래스가 있는 곳이고 com.nice.controller에는 컨트롤러 클래스가 있습니다.
스프링이 콩에 접근할 수 있도록 com.nice.controller 패키지를 com.nice.application으로 이동합니다.
도움이 될 경우를 대비한 또 다른 해결책: 제 경우, 제 경우, 문제는@RequestMapping("/xxx")클래스 레벨(컨트롤러 내) 및 노출된 서비스@PostMapping (value = "/yyyy")그리고.@GetMapping (value = "/zzz"); 코멘트를 하면@RequestMapping("/xxx")모든 것을 방법적인 수준에서 관리하고, 마법처럼 작동했습니다.
저에게 있어서 문제는 어플리케이션이 기동 후 항상 즉시 종료되도록 설정되어 있었다는 것입니다.그래서 컨트롤러에 접속할 수 있는지 시험했을 때 어플리케이션은 더 이상 실행되고 있지 않았습니다.즉시 셧다운하는 문제는 이 스레드로 해결됩니다.
@SpringBootApplication @ComponentScan(basePackages = {"com.rest"}) // basePackageClasses = HelloController.class) // 위의 구성 요소 검색을 사용하여 공용 클래스 RestfulWebServices Application {} 패키지를 추가합니다.
public static void main(String[] args) {
SpringApplication.run(RestfulWebServicesApplication.class, args);
}
}
이 에러의 원인에는, 다음의 3가지가 있습니다.
1 >
요청하신 URL이 올바른지 확인
2 > 고객님이 고객님께
MVC를 사용하여 @Controller를 사용하고 그렇지 않으면 @RestController를 사용합니다.
3 > 체크
컨트롤러 패키지(또는 클래스)를 루트 패키지 외부에 배치했는지 여부: com.example.demo ->가 메인 패키지입니다.
컨트롤러 패키지를 com.displaces.controller 내부에 배치합니다.
저도 같은 문제가 있었습니다.왜냐하면 제가 이너클래스를 만들었기 때문입니다.@Configuration어떤 식으로든 성분 스캔을 금지시켰어요
반환 유형을 문자열에서 ResponseEntity로 변경
Like :
@RequestMapping( "/item" )
public ResponseEntity<String> getStockItem() {
return new ResponseEntity<String>("It's working...!", HttpStatus.OK);
}
예를 들어 service, controller가 springBoot.xyz 패키지에 있는 경우 springboot 어플리케이션클래스를 root 패키지에 배치합니다.그렇지 않으면 springBoot 패키지는 패키지 아래에 스캔되지 않습니다.
POM 안에 추가할 수 있습니다.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>XXXXXXXXX</version>
</dependency>
언급URL : https://stackoverflow.com/questions/31318107/spring-boot-cannot-access-rest-controller-on-localhost-404
'programing' 카테고리의 다른 글
| MySql에서 아포스트로피(')를 이스케이프하는 방법 (0) | 2022.12.20 |
|---|---|
| jQuery를 사용하여 폼 데이터를 JavaScript 개체로 변환 (0) | 2022.12.20 |
| inversedBy와 mappedBy의 차이점은 무엇입니까? (0) | 2022.12.10 |
| Larabel 5.1에서 원시 쿼리를 실행하는 방법 (0) | 2022.12.10 |
| JavaScript를 사용하여 현재 URL을 가져오시겠습니까? (0) | 2022.12.10 |
