【发布时间】:2019-04-26 14:42:58
【问题描述】:
Spring Boot 上的新手 pb,我无法将 RestController 添加到我的应用程序中。
以下是用于使用 maven 构建这个非常简单的应用程序的 2 个文件:
1) Application.java
package com.learn.hello;
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "com.learn.hello.controller")
@RestController
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@RequestMapping("/")
public String index() {
return "Greetings from Spring Boot!";
}
}
HelloController.java
package com.learn.hello.controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
@RestController
public class HelloController {
@RequestMapping("/titi")
public String index() {
return "Greetings from titi Boot!";
}
}
项目结构
/src/main/java/com/learn/hello/Application.java
/src/main/java/com/learn/hello/controller/HelloController.java
/target/*
/pom.xml
localhost:8080 有效
但 localhost:8080/titi 没有(404 未找到)
有什么想法吗? 谢谢
【问题讨论】:
-
你能显示你的启动日志吗?
-
你忘记提供请求方法 RequestMethod.GET : @RequestMapping(value = "/students", method = RequestMethod.GET) 你可以使用@GetMapping("/titi") 代替@RequestMapping(" /titi")
-
从 Application 类中移除 @restcontroller 和 ComponentScan
-
这太奇怪了,一切似乎都很好,我唯一能做的就是删除@ComponentScan,因为它已经包含在@SpringBootApplication 中的控制器已经执行了/Application 的@ComponentScan。 java /src/main/java/com/**
-
重复它太奇怪了,我测试了同样的你的类,在我的本地环境中它的工作! perapsh 您的问题出在其他地方,请分享有关您项目的更多详细信息
标签: spring spring-boot