Spring Boot : localhost에서 REST 컨트롤러에 액세스 할 수 없음 (404)
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>
스타터 애플리케이션 :
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에 액세스
- 다른
@RequestMapping("/")
클래스 수준의ItemInventoryController
내가 이해하는 한, Spring Boot를 사용할 때 애플리케이션 컨텍스트가 필요하지 않습니다. 내가 맞아?
URL을 통해 메소드에 액세스하려면 다른 무엇을해야합니까?
InventoryApp 클래스에 다음을 추가해보십시오.
@SpringBootApplication
@ComponentScan(basePackageClasses = ItemInventoryController.class)
public class InventoryApp {
...
spring-boot는 아래 패키지의 구성 요소를 스캔 com.nice.application
하므로 컨트롤러가있는 com.nice.controller
경우 명시 적으로 스캔해야합니다.
MattR의 대답에 추가 :
에 명시된 바와 같이 여기 , @SpringBootApplication
자동으로 필요한 주석을 삽입합니다 @Configuration
, @EnableAutoConfiguration
또한,와 @ComponentScan
; 그러나은 @ComponentScan
앱과 동일한 패키지에있는 구성 요소 만 찾습니다.이 경우 com.nice.application
컨트롤러는 com.nice.controller
. 앱이 application
패키지 에서 컨트롤러를 찾지 못했기 때문에 404가 표시되는 이유 입니다.
SpringBoot 개발자는 다른 클래스 위의 루트 패키지에서 기본 애플리케이션 클래스를 찾을 것을 권장합니다. 루트 패키지를 사용하면 basePackage 속성 을 지정하지 않고도 @ComponentScan 주석을 사용할 수 있습니다 . 자세한 정보 그러나 사용자 지정 루트 패키지가 있는지 확인하십시오.
아래 코드로 서비스를 실행 한 후 얻은 동일한 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"
}
이를 극복하는 방법은 2 가지가 있습니다.
방법 1) 패키지 구조의 시작 부분에 부팅 응용 프로그램을 배치하고 그 안에 모든 컨트롤러를 놓습니다. 예 : package com.spring.boot.app; -응용 프로그램을 부팅합니다 (예 : Main Method -SpringApplication.run (App.class, args);).
동일한 패키지 구조로 컨트롤러를 레스트 예제 : package com.spring.boot.app.rest;
Method 2)Explicitly define the Controller in the Bootup package.
Method 1 is more cleaner.
Hope this will help.
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.
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.
Replace @RequestMapping( "/item" )
with @GetMapping(value="/item", produces=MediaType.APPLICATION_JSON_VALUE)
.
Maybe it will help somebody.
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";
};
}
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.
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.
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.
It also works if we use as follows:
@SpringBootApplication(scanBasePackages = { "<class ItemInventoryController package >.*" })
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
Your URL should be, you are missing the application context: localhost:8080/SpringBootTest/item
'Development Tip' 카테고리의 다른 글
생성자에서 정적 최종 필드 초기화 (0) | 2020.10.06 |
---|---|
이 두 줄이 같은가요? (0) | 2020.10.06 |
[01-12] 범위가 예상대로 작동하지 않는 이유는 무엇입니까? (0) | 2020.10.06 |
열거 형 이름을 C에서 문자열로 변환하는 방법 (0) | 2020.10.06 |
유효성을위한 포인터 테스트 (C / C ++) (0) | 2020.10.06 |