本文共 1751 字,大约阅读时间需要 5 分钟。
在初次接触Spring Boot开发过程中,我按照官网指导,在项目的pom.xml中添加了必要的依赖项。首先,我创建了一个controller包,并在其中编写了HelloController类。该类使用了Spring Boot的注解,暴露了一个映射到"/hello"端点的RESTful服务方法。代码如下:
import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;@Controllerpublic class HelloController { @ResponseBody @RequestMapping("/hello") public String sayHello() { return "hello, This is my first Spring Boot!"; }} 接下来,我尝试编写一个MyBootRun类作为Spring Boot的主启动类。该类使用了@SpringBootApplication注解,并定义了一个main方法来启动应用程序。代码如下:
package com.bit.springboot;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class MyBootRun { public static void main(String[] args) { SpringApplication.run(MyBootRun.class, args); }} 当我尝试运行main方法时,控制台输出显示应用程序启动失败。错误信息指出Tomcat连接器启动失败,提示端口8080可能已被占用或配置错误。我意识到可能有其他程序正在占用该端口,因此决定检查端口状态。
使用命令netstat -ano查看端口占用情况,发现8080端口正在被进程3508占用。进一步使用netstat -aon | findstr "8080"快速定位到占用端口的进程。通过任务管理器终止了占用8080端口的Java进程后,再次运行main方法。
然而,问题依然存在,8080端口再次被占用,进程PID变为6655。经过检查,发现这次占用的是java.exe进程。再次通过任务管理器终止该进程后,重新运行main方法。
此时,我尝试在浏览器中访问http://localhost:8080/hello,却发现页面无法正常显示。根据其他开发者的建议,我意识到可能是项目目录结构问题。查看项目目录路径,发现MyBootRun类位于com.bit.springboot.po包下,而po包通常用于持久化层(如数据库映射类),这可能导致Spring Boot无法正确读取主启动类。
为了修复这个问题,我将MyBootRun类所在的包名称更改为com.bit.springboot,确保项目结构符合Spring Boot的标准目录规范。调整后,再次运行main方法。
尽管问题暂时解决,但我再次发现8080端口被占用,进程PID为6655。经过检查,确认是java.exe进程再次占用端口。通过任务管理器终止该进程后,重新运行main方法。
这一次,我在浏览器中输入了http://localhost:8080/hello,成功显示了预期的响应信息:"hello, This is my first Spring Boot!"。问题得到彻底解决。
转载地址:http://zdjh.baihongyu.com/