1. Spring Boot概述
Spring Boot是Spring框架的扩展,旨在简化Spring应用的初始搭建和开发过程。它提供了自动配置、嵌入式服务器、生产就绪特性等功能,使开发者能够快速构建生产级别的应用。更多学习教程www.fgedu.net.cn
2. Spring Boot环境搭建
搭建Spring Boot开发环境需要JDK和构建工具(如Maven或Gradle)。
# java -version
java version “17.0.11” 2024-04-16 LTS
# 检查Maven版本
# mvn -version
Apache Maven 3.8.8
# 安装Spring Boot CLI(可选)
# wget https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.7.18/spring-boot-cli-2.7.18-bin.tar.gz
# tar -zxvf spring-boot-cli-2.7.18-bin.tar.gz -C /usr/local/
# export PATH=/usr/local/spring-2.7.18/bin:$PATH
# spring –version
Spring Boot CLI v2.7.18
3. 创建Spring Boot项目
可以使用Spring Initializr创建Spring Boot项目,支持网页界面和命令行方式。学习交流加群风哥微信: itpux-com
# 访问: https://start.spring.io/
# 选择项目类型、语言、Spring Boot版本
# 添加依赖
# 生成并下载项目
# 使用Maven命令创建项目
# mvn archetype:generate -DgroupId=com.example -DartifactId=demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
# 使用Spring Boot CLI创建项目
# spring init –dependencies=web,data-jpa demo
4. Spring Boot配置
Spring Boot使用application.properties或application.yml文件进行配置。
server.port=8080
spring.application.name=demo
# 数据库配置
spring.datasource.url=jdbc:mysql://fgedudb:3306/test
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
server:
port: 8080
spring:
application:
name: demo
datasource:
url: jdbc:mysql://fgedudb:3306/test
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
5. Spring Boot Web开发
Spring Boot提供了Spring MVC的自动配置,简化了Web开发。学习交流加群风哥QQ113257174
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping(“/hello”)
public String hello(@RequestParam(name = “name”, defaultValue = “World”) String name) {
return “Hello, ” + name + “!”;
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
// 运行应用
# mvn spring-boot:run
// 访问应用
# curl http://fgedudb:8080/hello
Hello, World!
6. Spring Boot数据访问
Spring Boot集成了Spring Data JPA、MyBatis等数据访问框架,简化了数据库操作。更多学习教程公众号风哥教程itpux_com
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getter和setter方法
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository
User findByEmail(String email);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User saveUser(User user) {
return userRepository.save(user);
}
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
public User getUserByEmail(String email) {
return userRepository.findByEmail(email);
}
}
7. Spring Boot测试
Spring Boot提供了强大的测试支持,包括单元测试和集成测试。
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
@SpringBootTest
public class HelloControllerTest {
@Test
public void testHello() {
HelloController controller = new HelloController();
String result = controller.hello(“Test”);
assertEquals(“Hello, Test!”, result);
}
}
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class WebIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHelloEndpoint() throws Exception {
mockMvc.perform(get(“/hello”))
.andExpect(status().isOk())
.andExpect(content().string(“Hello, World!”));
}
}
8. Spring Boot安全
Spring Boot集成了Spring Security,提供了认证和授权功能。
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(“/public/**”).permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(“/login”)
.permitAll()
.and()
.logout()
.permitAll();
}
}
9. Spring Boot部署
Spring Boot应用可以打包为jar或war文件,部署到各种环境中。author:www.itpux.com
# mvn clean package
# 运行jar文件
# java -jar target/demo-0.0.1-SNAPSHOT.jar
# 打包为war文件
# 修改pom.xml,将 packaging 改为 war
#
# 部署到Tomcat
# 将war文件复制到Tomcat的webapps目录
# 启动Tomcat
10. Spring Boot最佳实践
Spring Boot开发的最佳实践包括代码组织、性能优化、错误处理等方面。
/src
/main
/java
/com
/example
/controller // 控制器
/service // 业务逻辑
/repository // 数据访问
/model // 数据模型
/config // 配置类
/util // 工具类
/exception // 异常处理
/resources
/static // 静态资源
/templates // 模板文件
application.yml // 配置文件
/test
/java
/com
/example // 测试类
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleException(Exception e) {
return “Internal Server Error: ” + e.getMessage();
}
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleNotFoundException(NotFoundException e) {
return “Not Found: ” + e.getMessage();
}
}
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
