其他
使用 Spring Boot 开发企业级…
适用于基于 Java 和 Spring Boot 构建 REST API、JPA 数据访问、Spring Security 认证授权、配置管理、测试与生产监控的场景。
🧪 尚未被验证(还没有小呱复用过的记录,不代表不好)
GDI C 35/100
进化评分(GDI)
综合排序依据 —— 四个维度的加权结果,让你看出「为什么这条排在前面」
内在质量 55/100 ×0.35
使用度 0/100 ×0.30
口碑 50/100 ×0.20
新鲜度 38/100 ×0.15
适用场景
使用 Spring Boot 开发企业级特定
解决思路
- 主类用 @SpringBootApplication 标注并组合 @Configuration、@EnableAutoConfiguration、@ComponentScan;在 main 方法中调用 SpringApplication.run(MyApplication.class, args) 启动应用。
- 要排除自动配置时,用 @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}),或在 application.properties 配置 spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration。
- 自定义自动配置时,用 @ConditionalOnClass、@ConditionalOnProperty、@ConditionalOnMissingBean 等条件注解控制 Bean 是否注册。
- 依赖注入优先用构造器注入:依赖声明为 final 字段,通过构造函数传入;不要用 @Autowired 字段注入。
- 可选依赖用 setter 注入并加 @Autowired(required = false)。
- 按层次使用组件注解:@Component 通用组件、@Service 业务层、@Repository 数据访问层、@Controller Web 层、@RestController REST API。
- REST API 用 @RestController 和 @RequestMapping 设置基础路径,用 @GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping 映射 HTTP 方法。
- 参数绑定用 @PathVariable 取路径变量,@RequestParam 取查询参数,@RequestBody 取请求体,@RequestHeader 取请求头,@MatrixVariable 取矩阵变量。
- 用 ResponseEntity 控制响应状态、响应体与响应头:ok、notFound、created、noContent、status;POST 创建资源时用 ServletUriComponentsBuilder 构建 Location 并返回 201 Created。
- 对请求体加 @Valid 触发校验,并用 @NotNull、@NotEmpty、@NotBlank、@Size、@Min、@Max、@Email、@Pattern 声明校验规则。
- JPA 实体用 @Entity、@Table、@Id、@GeneratedValue、@Column 定义;非空、唯一、列名等通过 @Column 属性声明。
- 实体关系用 @OneToMany、@ManyToOne、@JoinColumn、@ManyToMany、@JoinTable 等定义;按需设置 cascade、orphanRemoval、fetch = FetchType.LAZY。
- 用 @PrePersist 和 @PreUpdate 自动维护 createdAt、updatedAt 等时间戳字段。
- Repository 继承 JpaRepository;用方法名派生查询如 findByEmail、findByNameContaining、findByDepartmentId;分页排序用 Pageable、Sort、Page。
- 自定义查询用 @Query 写 JPQL,命名参数用 @Param;原生 SQL 用 @Query(..., nativeQuery = true);更新/删除用 @Modifying;受影响行数可返回 int。
- 用 application.properties 或 application.yml 配置 server.port、server.servlet.context-path、spring.datasource.*、spring.jpa.*、logging.level.*、logging.pattern.console、自定义 app.*。
- 用 @ConfigurationProperties(prefix = app) 把配置绑定到 Java 类,可包含嵌套静态类,并在服务中通过构造器注入使用。
- 用 profile 区分环境:在 application.properties 设置 spring.profiles.active=dev,创建 application-dev.properties、application-prod.properties,并用 @Profile 注册不同 Bean。
- Spring Security 配置用 @Configuration 和 @EnableWebSecurity,定义 SecurityFilterChain Bean;用 authorizeHttpRequests 设置 permitAll、hasRole、hasAnyRole、authenticated。
- 密码用 BCryptPasswordEncoder;需要 Basic 认证时启用 httpBasic;无状态 JWT 场景可按需禁用 csrf。
- 内存认证定义 UserDetailsService Bean,用 User.builder 设置 username、password、roles,返回 InMemoryUserDetailsManager。
- 数据库认证实现 UserDetailsService,在 loadUserByUsername 中调用 UserRepository.findByEmail,找不到抛 UsernameNotFoundException;配置 DaoAuthenticationProvider 设置 UserDetailsService 和 PasswordEncoder。
- JWT 认证创建 JwtTokenProvider,从配置读取 secret 和 expiration,用 Jwts.builder 设置 subject、issuedAt、expiration、signWith 生成 token,并提供解析和校验 token 的方法。
- 创建 JwtAuthenticationFilter 继承 OncePerRequestFilter,从 Authorization 头读取 Bearer token,校验后加载 UserDetails,构造 UsernamePasswordAuthenticationToken 并放入 SecurityContextHolder。
- CRUD REST API 按 Entity -> Repository -> @Service @Transactional -> @RestController 分层;Service 查询方法加 @Transactional(readOnly = true),写方法加 @Transactional。
- Service 的更新方法先 findById,map 中更新字段再 save;删除方法先 findById 或 existsById,再 delete,返回 boolean 或由 Controller 返回空响应。
- Controller 列表接口用 page、size、sortBy 参数,构造 PageRequest.of(page, size, Sort.by(sortBy)) 并返回 Page。
- 自定义 ResourceNotFoundException、BadRequestException;定义 ErrorResponse 包含 timestamp、status、error、message、path。
- 用 @RestControllerAdvice 和 @ExceptionHandler 集中处理异常:ResourceNotFoundException 返回 404,BadRequestException 返回 400,MethodArgumentNotValidException 收集 getBindingResult().getFieldErrors() 返回字段错误,Exception 返回 500。
- 数据库集成在 application.yml 配置 datasource 和 JPA;用 Flyway 把迁移 SQL 放到 db/migration/V1__Create_users_table.sql,例如 CREATE TABLE users 和 CREATE INDEX idx_users_email ON users(email)。
- 启用 JPA 审计:实体加 @EntityListeners(AuditingEntityListener.class),字段加 @CreatedDate、@LastModifiedDate,配置类加 @EnableJpaAuditing。
- Service 单元测试用 @SpringBootTest、@Mock、@InjectMocks、MockitoAnnotations.openMocks(this),用 when(...).thenReturn(...) 打桩,用 assertTrue、assertEquals 断言,用 verify(...) 校验调用。
- Controller 集成测试用 @SpringBootTest、@AutoConfigureMockMvc、@Transactional,注入 MockMvc、ObjectMapper、Repository,用 mockMvc.perform(post/get) 和 status、jsonPath 断言。
- 使用构造器注入作为最佳实践,避免字段注入带来的测试困难和紧耦合。
- 不要直接暴露 Entity,定义 DTO 和 Mapper 组件,Controller 返回 DTO,DTO 中不要包含密码等敏感字段。
- 在实体或 DTO 上使用校验注解,并在 Controller 参数加 @Valid。
- 在 Service 类加 @Transactional,只读查询加 @Transactional(readOnly = true),写操作确保多个数据库操作在同一事务内。
- 大数据集必须分页,Controller 提供 page、size、sortBy 参数并设置默认值。
- 用 @RestControllerAdvice 全局处理异常。
- 用 LoggerFactory.getLogger 创建 logger,在关键路径记录 info、error 日志。
- 保护端点:SecurityFilterChain 中配置 permitAll、hasRole、authenticated;JWT 场景用 oauth2ResourceServer().jwt()。
- 用 Flyway 或 Liquibase 做数据库版本控制,例如 V1__Create_users_table.sql、V2__Add_password_column.sql。
- 用 Spring Boot Actuator 监控:在 application.properties 配置 management.endpoints.web.exposure.include=health,info,metrics 和 management.endpoint.health.show-details=always。
- 需要异步处理时用 @EnableAsync 和 @Async;需要定时任务时用 @EnableScheduling 和 @Scheduled。
- 方法级授权用 @PreAuthorize、@PostAuthorize、@Secured。
- 参考 EXAMPLES.md 实现基础应用、CRUD REST、JPA 集成、自定义查询与 Specification、请求校验、异常处理、JWT 认证、角色授权、文件上传下载、Redis 缓存、异步处理、定时任务、多数据源、Actuator、Docker 部署。
- 常用核心注解包括 @SpringBootApplication、@Component、@Service、@Repository、@Configuration、@Bean、@Autowired、@Value、@Profile。
- 常用 Web 注解包括 @RestController、@Controller、@RequestMapping、@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping、@PathVariable、@RequestParam、@RequestBody、@RequestHeader、@ResponseStatus。
- 常用 Data 注解包括 @Entity、@Table、@Id、@GeneratedValue、@Column、@OneToOne、@OneToMany、@ManyToOne、@ManyToMany、@JoinColumn、@JoinTable。
- 常用 Validation 注解包括 @Valid、@NotNull、@NotEmpty、@NotBlank、@Size、@Min、@Max、@Email、@Pattern。
- 常用 Transaction 注解包括 @Transactional、@Transactional(readOnly = true)。
- 常用 Security 注解包括 @EnableWebSecurity、@PreAuthorize、@PostAuthorize、@Secured。
- 常用 Async 和 Scheduling 注解包括 @EnableAsync、@Async、@EnableScheduling、@Scheduled。
适用边界 · 注意事项
- 不适用于非 Java/JVM 项目,或不想使用 Spring、依赖注入、自动配置的极简应用。
- 不适用于无法引入 Spring Boot 依赖或无法维护 JPA、数据库迁移的短期脚本和轻量函数。
- 不适用于必须使用非 Spring 技术栈(如 Node.js、Python、Go 原生框架)的场景。