本文全面介绍了Spring Boot学习的相关内容,包括Spring Boot的核心特点、开发环境搭建、项目创建以及常用配置和功能开发。文章还详细讲解了Spring Boot应用的打包和部署方法,帮助开发者快速上手并掌握Spring Boot开发技能。在Spring Boot学习过程中,你将了解从环境搭建到项目开发的全流程,轻松掌握Spring Boot的各项高级功能。
Spring Boot是Spring框架的一个模块,旨在简化Spring应用的创建、配置和部署。它提供了一种新的方式来快速构建独立的、生产级别的基于Spring的应用程序。Spring Boot的核心目标是简化配置,使开发者可以快速上手开发,而不需要深入了解复杂的配置细节。
安装Java JDK:
# Windows 系统示例 set JAVA_HOME=C:\Program Files\Java\jdk-11 set PATH=%JAVA_HOME%\bin;%PATH% # Linux 系统示例 export JAVA_HOME=/usr/lib/jvm/java-11-openjdk export PATH=$JAVA_HOME/bin:$PATH
安装IntelliJ IDEA:
使用Spring Initializr生成项目:
mvn clean install
或gradle clean build
命令进行构建。访问Spring Initializr:
解压项目:
src/main/java
:存放Java源代码。src/main/resources
:存放配置文件和静态资源。src/test/java
:存放测试代码。pom.xml
(Maven项目)或build.gradle
(Gradle项目):项目构建配置文件。src/main/resources/application.properties
或application.yml
:应用配置文件。my-spring-boot-app/ ├── src │ ├── main │ │ ├── java │ │ │ └── com │ │ │ └── example │ │ │ └── myapp │ │ │ ├── MyApplication.java │ │ │ └── controller │ │ │ └── HelloController.java │ │ └── resources │ │ ├── application.properties │ │ └── static │ │ └── index.html │ └── test │ └── java │ └── com │ └── example │ └── myapp │ └── MyApplicationTests.java ├── pom.xml └── .gitignore
运行应用:
MyApplication
类中的main
方法启动应用。mvn spring-boot:run
(Maven)或./gradlew bootRun
(Gradle)。http://localhost:8080
查看应用运行状态。// MyApplication.java package com.example.myapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } // HelloController.java package com.example.myapp.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/") public String hello() { return "Hello World!"; } }
@SpringBootApplication
是Spring Boot中最重要的注解之一,它组合了多个注解的功能:
@Configuration
:标记类为Spring配置类。@EnableAutoConfiguration
:标记类为自动配置类。@ComponentScan
:标记类用于组件扫描,指定扫描包路径。package com.example.myapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } }
这些注解用于定义不同类型的组件:
@Controller
:用于标记控制器类。@Service
:用于标记服务类。@Repository
:用于标记数据访问类。@Component
:通用注解,标记任何Spring组件。// HelloController.java package com.example.myapp.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/") public String hello() { return "Hello World!"; } } // UserService.java package com.example.myapp.service; import org.springframework.stereotype.Service; @Service public class UserService { } // UserRepository.java package com.example.myapp.repository; import org.springframework.stereotype.Repository; @Repository public class UserRepository { } // MyComponent.java package com.example.myapp; import org.springframework.stereotype.Component; @Component public class MyComponent { }
这些配置文件用于定义应用的各种属性,如数据库连接信息、端口号等。
# application.properties server.port=8080 spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root
# application.yml server: port: 8080 spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: root
开发RESTful API需要使用@RestController
和@RequestMapping
注解。
// UserController.java package com.example.myapp.controller; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; @RestController public class UserController { private List<User> users = new ArrayList<>(); @GetMapping("/users") public List<User> getAllUsers() { return users; } @PostMapping("/users") public User addUser(@RequestBody User user) { users.add(user); return user; } } class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } // Getters and setters }
使用Spring Data JPA进行数据库连接和操作。
pom.xml
或build.gradle
中添加Spring Data JPA依赖。<!-- pom.xml 示例 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
// build.gradle 示例 implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
application.properties
或application.yml
中配置数据库连接信息。# application.properties spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=root spring.jpa.hibernate.ddl-auto=update
# application.yml spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: root jpa: hibernate: ddl-auto: update
@Entity
注解。// User.java package com.example.myapp.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private int age; // Getters and setters }
JpaRepository
。// UserRepository.java package com.example.myapp.repository; import com.example.myapp.model.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Long> { }
// UserService.java package com.example.myapp.service; import com.example.myapp.model.User; import com.example.myapp.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public List<User> getAllUsers() { return userRepository.findAll(); } public User addUser(User user) { return userRepository.save(user); } }
文件上传和下载通常涉及文件存储和访问。
application.properties
或application.yml
中配置文件存储路径。# application.properties spring.servlet.multipart.location=upload/
# application.yml spring: servlet: multipart: location: upload/
@RequestParam
和@PostMapping
处理文件上传请求。// FileController.java package com.example.myapp.controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @RestController public class FileController { private static final String UPLOAD_DIR = "upload/"; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { Path uploadPath = Paths.get(UPLOAD_DIR); // Create directory if not exists if (!Files.exists(uploadPath)) { Files.createDirectories(uploadPath); } // Save the file to upload directory try { Files.write(Paths.get(UPLOAD_DIR + file.getOriginalFilename()), file.getBytes()); } catch (IOException e) { throw new RuntimeException("Failed to save file", e); } return "File saved successfully"; } }
@GetMapping
处理文件下载请求。// FileController.java (continued) @GetMapping("/download/{filename}") public void downloadFile(@PathVariable String filename, HttpServletResponse response) throws IOException { Path downloadPath = Paths.get(UPLOAD_DIR + filename); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); Files.copy(downloadPath, response.getOutputStream()); response.flushBuffer(); }
mvn clean package
这将生成target
目录下的my-spring-boot-app.jar
文件。
./gradlew clean build
这将生成build/libs
目录下的my-spring-boot-app.jar
文件。
pom.xml
或build.gradle
配置打包为WAR包。<!-- pom.xml 示例 --> <packaging>war</packaging> <build> <finalName>my-spring-boot-app</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build>
// build.gradle 示例 plugins { id 'org.springframework.boot' version '2.5.5' id 'io.spring.dependency-management' version '1.0.11.RELEASE' id 'war' } war { baseName = 'my-spring-boot-app' version = '1.0.0' }
webapps
目录下,启动Tomcat服务器。# 复制WAR文件到Tomcat cp my-spring-boot-app-1.0.0.war /path/to/tomcat/webapps/
启动Tomcat服务器:
# 启动Tomcat /path/to/tomcat/bin/startup.sh
访问http://localhost:8080/my-spring-boot-app
查看应用运行状态。
# 部署WAR文件到Tomcat cp my-spring-boot-app-1.0.0.war /opt/tomcat/webapps/
# 部署WAR文件到Tomcat cp my-spring-boot-app-1.0.0.war /opt/tomcat/webapps/ `` 通过以上步骤可以将Spring Boot应用部署到云平台,确保应用可以稳定运行。