🚀 SpringBoot核心知识点
一、基础核心 🌱
1. 自动配置原理
-
核心注解 🎯
- @SpringBootApplication
- @EnableAutoConfiguration
- @SpringBootConfiguration
- @ComponentScan
-
自动配置流程 ⚙️
- 加载META-INF/spring.factories
- 加载AutoConfiguration类
- 条件注解过滤
- 加载配置类
-
条件注解 🔍
- @ConditionalOnClass
- @ConditionalOnMissingClass
- @ConditionalOnBean
- @ConditionalOnMissingBean
- @ConditionalOnProperty
- @ConditionalOnWebApplication
2. 配置体系 📝
-
配置文件类型
- properties文件
- yaml文件
- 环境变量
- 命令行参数
-
配置加载顺序
- bootstrap配置
- application配置
- 外部配置
-
配置注解
- @Value
- @ConfigurationProperties
- @PropertySource
- @ImportResource
二、Web开发 🌐
1. Web配置核心
-
接口开发
- @RestController
- @RequestMapping
- @ResponseBody
- @RequestBody
-
异常处理
- @ControllerAdvice
- @ExceptionHandler
- @ResponseStatus
-
参数校验
- @Validated
- @Valid
- 校验注解
2. 应用容器配置
-
内嵌容器
- Tomcat
- Jetty
- Undertow
-
容器配置
- 端口配置
- 上下文路径
- SSL配置
- Session配置
三、数据访问 💾
1. 数据源配置
-
连接池
- HikariCP
- Druid
- Tomcat Pool
-
多数据源
- 动态数据源
- 主从配置
- 分库分表
2. ORM支持
-
JPA集成
- 实体映射
- Repository接口
- 查询方法
-
MyBatis集成
- Mapper接口
- XML配置
- 注解开发
四、事务管理 💼
1. 事务核心概念
-
事务特性
- 原子性
- 一致性
- 隔离性
- 持久性
-
事务传播行为
- REQUIRED
- REQUIRES_NEW
- SUPPORTS
- NOT_SUPPORTED
- MANDATORY
- NEVER
- NESTED
-
事务隔离级别
- READ_UNCOMMITTED
- READ_COMMITTED
- REPEATABLE_READ
- SERIALIZABLE
五、缓存支持 ⚡
1. 缓存框架
-
Spring缓存抽象
- @Cacheable
- @CachePut
- @CacheEvict
- @CacheConfig
-
缓存管理器
- ConcurrentMapCacheManager
- EhCacheCacheManager
- RedisCacheManager
六、消息服务 📨
1. 消息集成
-
JMS支持
- ActiveMQ集成
- 消息监听器
-
AMQP支持
- RabbitMQ集成
- 消息模板
七、安全管理 🔒
1. 安全框架
-
Spring Security
- 认证
- 授权
- 会话管理
- CSRF防护
-
安全控制
- 接口安全
- 方法安全
- 资源访问控制
八、监控管理 📊
1. Spring Boot Actuator
-
端点监控
- Health检查
- Metrics指标
- Logging日志
- Thread dump
-
安全审计
- 审计事件
- 审计日志
九、测试支持 🧪
1. 测试框架
-
单元测试
- @SpringBootTest
- @AutoConfigureMockMvc
- TestRestTemplate
-
集成测试
- 测试切片
- Mock测试
- 测试工具类
十、部署运维 🛠️
1. 部署方式
-
打包方式
- JAR部署
- WAR部署
- Docker容器
-
运维特性
- 优雅停机
- 健康检查
- 配置热更新
- 日志管理
📚 核心知识入门
一、基础篇 🌱
1. 核心特性
-
自动配置
@SpringBootApplication // 等同于以下三个注解 @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan
-
起步依赖
<!-- 父依赖 --> <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.0</version> </parent><!-- Web启动器 --> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency>
2. 配置管理 ⚙️
2.1 配置文件
# application.yml
server:port: 8080spring:application:name: demo-service# 多环境配置profiles:active: dev
2.2 配置注入
// 方式一:@Value
@Value("${server.port}")
private Integer port;// 方式二:@ConfigurationProperties
@Component
@ConfigurationProperties(prefix = "server")
public class ServerProperties {private Integer port;// getter/setter
}// 方式三:@Environment
@Autowired
private Environment env;
String port = env.getProperty("server.port");
2.3 配置优先级
- 命令行参数
- java:comp/env里的JNDI属性
- JVM系统属性
- 操作系统环境变量
- random.*属性
- application.properties/yml
3. Web开发 🌐
3.1 REST接口
@RestController
@RequestMapping("/api/users")
public class UserController {@GetMapping("/{id}")public User getUser(@PathVariable Long id) {return userService.getById(id);}@PostMappingpublic Result<User> createUser(@RequestBody @Validated User user) {return Result.success(userService.save(user));}@PutMapping("/{id}")public void updateUser(@PathVariable Long id, @RequestBody User user) {user.setId(id);userService.update(user);}@DeleteMapping("/{id}")public void deleteUser(@PathVariable Long id) {userService.delete(id);}
}
3.2 静态资源
spring:mvc:static-path-pattern: /static/**web:resources:static-locations: classpath:/static/
3.3 拦截器
@Component
public class AuthInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {// 前置处理return true;}
}@Configuration
public class WebConfig implements WebMvcConfigurer {@Autowiredprivate AuthInterceptor authInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(authInterceptor).addPathPatterns("/**").excludePathPatterns("/login");}
}
4. 数据访问 📊
4.1 JPA集成
// 实体类
@Entity
@Table(name = "user")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;@Column(length = 32, nullable = false)private String username;
}// Repository接口
@Repository
public interface UserRepository extends JpaRepository<User, Long> {Optional<User> findByUsername(String username);
}
4.2 MyBatis集成
// Mapper接口
@Mapper
public interface UserMapper {@Select("SELECT * FROM user WHERE id = #{id}")User getById(@Param("id") Long id);@Insert("INSERT INTO user(username, password) VALUES(#{username}, #{password})")void insert(User user);
}
4.3 多数据源配置
spring:datasource:primary:url: jdbc:mysql://localhost:3306/db1username: rootpassword: rootsecondary:url: jdbc:mysql://localhost:3306/db2username: rootpassword: root
@Configuration
public class DataSourceConfig {@Primary@Bean@ConfigurationProperties("spring.datasource.primary")public DataSource primaryDataSource() {return DataSourceBuilder.create().build();}@Bean@ConfigurationProperties("spring.datasource.secondary")public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();}
}
5. 事务管理 💼
5.1 声明式事务
@Service
public class UserService {@Transactional(rollbackFor = Exception.class)public void createUser(User user) {// 业务逻辑}@Transactional(readOnly = true)public User getUser(Long id) {return userRepository.findById(id).orElse(null);}
}
5.2 编程式事务
@Autowired
private TransactionTemplate transactionTemplate;public void createUser(User user) {transactionTemplate.execute(new TransactionCallbackWithoutResult() {@Overrideprotected void doInTransactionWithoutResult(TransactionStatus status) {try {// 业务逻辑} catch (Exception e) {status.setRollbackOnly();}}});
}
6. 缓存支持 📦
6.1 注解缓存
@Service
@CacheConfig(cacheNames = "users")
public class UserService {@Cacheable(key = "#id")public User getUser(Long id) {return userRepository.findById(id).orElse(null);}@CachePut(key = "#user.id")public User updateUser(User user) {return userRepository.save(user);}@CacheEvict(key = "#id")public void deleteUser(Long id) {userRepository.deleteById(id);}
}
6.2 Redis配置
spring:redis:host: localhostport: 6379password: database: 0
@Configuration
public class RedisConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);// 配置序列化方式template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());return template;}
}