Token导航 LogoToken导航TokenDH.com
开发规范需要联网unknown未标认证来源可访问许可证需确认审计未展示

spring-boot-best-practices春季启动最佳实践

Agent Skill

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

总安装

30,915

周安装

833

下载量

11,747
Local Agent

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:spring-boot-best-practices(春季启动最佳实践)
来源仓库:https://smithery.ai
仓库路径:spring-boot-best-practices
安装命令:
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。当前暂无明确安装命令,请以来源页面说明为准。

简介

汇集 Spring Boot 应用开发的权威最佳实践知识库。

  • 适用于架构评审、代码规范制定与技术债务治理参考。
  • 涵盖配置管理、异常处理与部署运维的标准化建议。
  • 不同规模团队可根据实际情况选择性采纳部分准则。
  • 实践指南需定期更新以匹配框架演进方向。spring-boot-best-practices 属于开发规范类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Spring Boot Code Generation Guidelines

When generating or reviewing Spring Boot code, follow these best practices:

Dependency Injection

  • Use constructor injection, never field injection with @Autowired
  • Mark injected fields as private final
  • Let Lombok's @RequiredArgsConstructor generate constructors when appropriate
// Good
@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;
    private final EmailService emailService;
}

// Avoid
@Service
public class UserService {
    @Autowired
    private UserRepository userRepository; // Field injection - avoid
}

Package Structure

Follow standard Spring Boot layering:

com.example.project/
├── controller/       # REST endpoints, @RestController
├── service/          # Business logic, @Service
├── repository/       # Data access, extends JpaRepository
├── model/            # JPA entities, @Entity
├── dto/              # Data transfer objects
├── config/           # Configuration classes, @Configuration
└── exception/        # Custom exceptions and @ControllerAdvice

REST Controllers

  • Use proper HTTP methods (GET, POST, PUT, DELETE, PATCH)
  • Return ResponseEntity<T> for explicit status codes
  • Use @Valid for request body validation
  • Include API versioning in paths (e.g., /api/v1/users)
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {
    private final UserService userService;

    @GetMapping("/{id}")
    public ResponseEntity<UserDto> getUser(@PathVariable Long id) {
        return userService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<UserDto> createUser(@Valid @RequestBody CreateUserRequest request) {
        UserDto created = userService.create(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(created);
    }
}

Service Layer

  • Keep services focused on business logic
  • Use Optional<T> for potentially absent results
  • Throw custom exceptions for business rule violations
  • Add @Transactional where needed
@Service
@RequiredArgsConstructor
public class UserService {
    private final UserRepository userRepository;

    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }

    @Transactional
    public User create(CreateUserRequest request) {
        if (userRepository.existsByEmail(request.getEmail())) {
            throw new UserAlreadyExistsException(request.getEmail());
        }
        User user = new User(request.getName(), request.getEmail());
        return userRepository.save(user);
    }
}

JPA Entities

  • Use @Entity and @Table annotations
  • Include @Id with generation strategy
  • Use Lombok annotations: @Data, @NoArgsConstructor, @AllArgsConstructor
  • Include proper relationships with @OneToMany, @ManyToOne, etc.
@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false, unique = true)
    private String email;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
    private List<Order> orders = new ArrayList<>();
}

Testing Requirements

For every component generated:

  1. Controller Tests - Use @WebMvcTest and MockMvc
  2. Service Tests - Use @ExtendWith(MockitoExtension.class) with mocks
  3. Repository Tests - Use @DataJpaTest with test database
  4. Integration Tests - Use @SpringBootTest for end-to-end scenarios
@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    void getUser_WhenExists_ReturnsUser() throws Exception {
        // Arrange
        UserDto user = new UserDto(1L, "John Doe", "john@example.com");
        when(userService.findById(1L)).thenReturn(Optional.of(user));

        // Act & Assert
        mockMvc.perform(get("/api/v1/users/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("John Doe"));
    }
}

Documentation

  • Add comprehensive JavaDoc for public methods
  • Include @param, @return, and @throws tags
  • Document business rules and assumptions
  • Use OpenAPI/Swagger annotations for REST endpoints
/**
 * Creates a new user in the system.
 *
 * @param request the user creation request containing name and email
 * @return the created user with generated ID
 * @throws UserAlreadyExistsException if a user with the email already exists
 */
@Transactional
public User create(CreateUserRequest request) {
    // implementation
}

Error Handling

  • Create custom exceptions extending RuntimeException
  • Use @ControllerAdvice for global exception handling
  • Return proper HTTP status codes with error details
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleUserNotFound(UserNotFoundException ex) {
        ErrorResponse error = new ErrorResponse(
            HttpStatus.NOT_FOUND.value(),
            ex.getMessage()
        );
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }
}

Configuration

  • Use application.yml over application.properties
  • Externalize configuration values
  • Use Spring profiles for environment-specific config
spring:
  datasource:
    url: jdbc:postgresql://localhost:5432/mydb
    username: ${DB_USERNAME}
    password: ${DB_PASSWORD}
  jpa:
    hibernate:
      ddl-auto: validate
    show-sql: false

When This Skill Activates

This skill automatically activates when:

  • Generating Spring Boot controllers, services, or repositories
  • Creating JPA entities or DTOs
  • Writing Spring Boot tests
  • Reviewing existing Spring Boot code
  • Questions about Spring Boot best practices

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Local Agent

71.23%
按下载量换算8,367

安全审计

暂无安全审计结果可展示。

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills