Spring Boot入门教程 Spring Boot简介 Spring Boot是Spring团队开发的一个框架,旨在简化Spring应用的初始搭建和开发过程。它采用了”约定优于配置”的原则,大量减少了开发人员的配置工作,让开发者能够更加专注于业务逻辑的实现,而不是项目的配置细节。
Spring Boot的主要特点包括:
创建独立的Spring应用程序
内嵌Tomcat、Jetty或Undertow(无需部署WAR文件)
提供”固定的”starter依赖,简化构建配置
尽可能自动配置Spring和第三方库
提供生产级特性,如指标、健康检查和外部化配置
完全不需要XML配置
创建Spring Boot项目 使用Spring Initializr 最简单的方式是使用Spring Initializer 创建一个新项目。
也可以通过IDE如IntelliJ IDEA或Eclipse的Spring Boot插件创建项目。
使用Maven 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <parent > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-parent</artifactId > <version > 2.6.7</version > </parent > <dependencies > <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-web</artifactId > </dependency > </dependencies > <build > <plugins > <plugin > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-maven-plugin</artifactId > </plugin > </plugins > </build >
第一个Spring Boot应用 创建一个简单的Spring Boot应用非常容易:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 package com.example.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;@SpringBootApplication @RestController public class DemoApplication { public static void main (String[] args) { SpringApplication.run(DemoApplication.class, args); } @GetMapping("/hello") public String hello () { return "Hello, Spring Boot!" ; } }
这段代码实现了以下功能:
@SpringBootApplication
注解表示这是一个Spring Boot应用
@RestController
注解表示这是一个RESTful风格的控制器
main
方法启动了Spring Boot应用
hello
方法映射到”/hello”路径,返回一个字符串
Spring Boot核心注解 @SpringBootApplication @SpringBootApplication
是一个便利注解,它结合了以下三个注解:
@Configuration
:表示该类是一个配置类
@EnableAutoConfiguration
:开启Spring Boot的自动配置机制
@ComponentScan
:启用组件扫描,自动发现和注册Bean
@RestController和@Controller @RestController
是@Controller
和@ResponseBody
的组合,用于创建RESTful Web服务:
1 2 3 4 5 6 7 8 @RestController public class UserController { @GetMapping("/users/{id}") public User getUser (@PathVariable Long id) { } }
@RequestMapping及其变体 用于处理请求映射:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @RestController @RequestMapping("/api") public class ApiController { @GetMapping("/users") public List<User> getUsers () { } @PostMapping("/users") public User createUser (@RequestBody User user) { } }
配置管理 application.properties/application.yml Spring Boot使用application.properties
或application.yml
文件进行配置。两种格式的配置文件都支持,但YAML格式更加结构化和可读。
application.properties示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 server.port =8080 server.servlet.context-path =/api spring.datasource.url =jdbc:mysql://localhost:3306/mydb spring.datasource.username =root spring.datasource.password =password spring.datasource.driver-class-name =com.mysql.cj.jdbc.Driver spring.jpa.hibernate.ddl-auto =update spring.jpa.show-sql =true
application.yml示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 server: port: 8080 servlet: context-path: /api spring: datasource: url: jdbc:mysql://localhost:3306/mydb username: root password: password driver-class-name: com.mysql.cj.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true
@ConfigurationProperties 使用@ConfigurationProperties
可以将配置文件中的属性绑定到Java对象:
1 2 3 4 5 6 7 8 9 10 11 @Configuration @ConfigurationProperties(prefix = "mail") public class MailProperties { private String host; private int port; private String username; private String password; }
对应的配置文件:
1 2 3 4 5 mail: host: smtp.gmail.com port: 587 username: user@gmail.com password: secret
配置文件的优先级 Spring Boot配置的加载顺序(优先级从高到低):
命令行参数
SPRING_APPLICATION_JSON
系统环境变量
特定profile的应用程序属性(application-{profile}.properties/yml)
应用程序属性(application.properties/yml)
@PropertySource注解
默认属性
Spring Boot Starter依赖 Starter依赖是Spring Boot的一个重要特性,它是一组依赖描述符,可以方便地将相关的依赖包含到项目中:
spring-boot-starter-web
:Web和RESTful应用程序
spring-boot-starter-data-jpa
:Spring Data JPA和Hibernate
spring-boot-starter-security
:Spring Security
spring-boot-starter-test
:单元测试,包括JUnit、Hamcrest和Mockito
spring-boot-starter-actuator
:生产就绪功能,帮助监控和管理应用
数据访问 Spring Data JPA Spring Boot简化了与数据库的交互,特别是通过Spring Data JPA:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String email; } public interface UserRepository extends JpaRepository <User, Long> { User findByUsername (String username) ; List<User> findByEmailContaining (String email) ; @Query("SELECT u FROM User u WHERE u.email LIKE %:domain%") List<User> findByEmailDomain (@Param("domain") String domain) ; }
使用JdbcTemplate 对于简单的数据库操作,可以使用JdbcTemplate
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @Repository public class JdbcUserRepository { private final JdbcTemplate jdbcTemplate; public JdbcUserRepository (JdbcTemplate jdbcTemplate) { this .jdbcTemplate = jdbcTemplate; } public List<User> findAll () { return jdbcTemplate.query( "SELECT id, username, email FROM users" , (rs, rowNum) -> { User user = new User (); user.setId(rs.getLong("id" )); user.setUsername(rs.getString("username" )); user.setEmail(rs.getString("email" )); return user; } ); } }
RESTful Web服务 使用Spring Boot创建RESTful API非常简单:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 @RestController @RequestMapping("/api/users") public class UserController { private final UserService userService; public UserController (UserService userService) { this .userService = userService; } @GetMapping public List<User> getAllUsers () { return userService.findAll(); } @GetMapping("/{id}") public ResponseEntity<User> getUserById (@PathVariable Long id) { User user = userService.findById(id); if (user != null ) { return ResponseEntity.ok(user); } else { return ResponseEntity.notFound().build(); } } @PostMapping @ResponseStatus(HttpStatus.CREATED) public User createUser (@RequestBody User user) { return userService.save(user); } @PutMapping("/{id}") public ResponseEntity<User> updateUser (@PathVariable Long id, @RequestBody User user) { if (userService.existsById(id)) { user.setId(id); return ResponseEntity.ok(userService.save(user)); } else { return ResponseEntity.notFound().build(); } } @DeleteMapping("/{id}") public ResponseEntity<Void> deleteUser (@PathVariable Long id) { if (userService.existsById(id)) { userService.deleteById(id); return ResponseEntity.noContent().build(); } else { return ResponseEntity.notFound().build(); } } }
Spring Boot自定义配置 @Bean和@Configuration 使用@Bean
和@Configuration
可以自定义配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 @Configuration public class AppConfig { @Bean public RestTemplate restTemplate () { return new RestTemplate (); } @Bean @ConditionalOnProperty(name = "cache.enabled", havingValue = "true") public CacheManager cacheManager () { return new ConcurrentMapCacheManager ("users" ); } }
排除自动配置 可以排除不需要的自动配置:
1 2 3 4 @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class MyApplication { }
单元测试 Spring Boot提供了强大的测试支持:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 @SpringBootTest class UserServiceTests { @Autowired private UserService userService; @MockBean private UserRepository userRepository; @Test void findByIdReturnsUser () { User user = new User (); user.setId(1L ); user.setUsername("test" ); when (userRepository.findById(1L )).thenReturn(Optional.of(user)); User found = userService.findById(1L ); assertThat(found).isNotNull(); assertThat(found.getUsername()).isEqualTo("test" ); } }
Spring Boot Actuator Actuator提供了许多生产就绪的特性,如监控和管理:
1 2 3 4 <dependency > <groupId > org.springframework.boot</groupId > <artifactId > spring-boot-starter-actuator</artifactId > </dependency >
配置Actuator端点:
1 2 3 4 5 6 7 8 management: endpoints: web: exposure: include: health,info,metrics,prometheus endpoint: health: show-details: always
总结 Spring Boot极大地简化了Spring应用程序的开发过程,通过自动配置和约定优于配置的原则,开发者可以快速构建出高质量的应用程序。无论是构建微服务、Web应用还是批处理系统,Spring Boot都提供了完善的支持,使开发者能够专注于业务逻辑而不是繁琐的配置细节。