按教材
下例选用IntelliJ IDEA 2024.3.3
付费版
创建项目
JDK
版本根据实际情况。
启动类简析
package com.example.demo; // 这段代码位于 com.example.demo 这个包下import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class Demo1Application { // 定义了一个 主类 Demo1Application,// 该类中包含 main 方法,作为程序的 入口,用来启动整个 Spring Boot 应用public static void main(String[] args) {SpringApplication.run(Demo1Application.class, args);}
}
@SpringBootApplication
是一个 核心注解,它相当于 三个注解的组合:
@Configuration // 标识该类是一个配置类,替代了传统的 XML 配置文件
@EnableAutoConfiguration // 启用 Spring Boot 自动配置功能
@ComponentScan // 允许 Spring 扫描该包及子包中的组件(如 Controller、Service 等)
pom.xml简析
该文件描述了项目的基本信息、依赖等
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><!--引入 Spring Boot Web 依赖,用于开发 Web 应用(包含 Tomcat、Jackson、Spring MVC 等)--></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope><!--spring-boot-starter-test:Spring Boot的测试依赖,scope=test表示仅用于测试,不会随正式构建一起打包--></dependency></dependencies>
创建Spring MVC控制器
package com.example.demo.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@RequestMapping("first")public String index() {System.out.println("第一个控制器正在运行~");return "这是一个springboot应用";}
}
运行
只有免费版IDEA
下例选用IntelliJ IDEA Community Edition 2024.2
创建项目
https://start.spring.io/
将压缩包解压后,以IDEA项目打开,其它同上。