Spring Boot Best Practices
БесплатноБез исполняемых скриптовНе проверенGenerate Spring Boot components following modern Java best practices and team conventions
Об этом скилле
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
@RequiredArgsConstructorgenerate 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
@Validfor 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
@Transactionalwhere 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
@Entityand@Tableannotations - Include
@Idwith 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:
- Controller Tests - Use
@WebMvcTestand MockMvc - Service Tests - Use
@ExtendWith(MockitoExtension.class)with mocks - Repository Tests - Use
@DataJpaTestwith test database - Integration Tests - Use
@SpringBootTestfor 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", "[email protected]");
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@throwstags - 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 `@Controlle
Установить Spring Boot Best Practices в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Spring Boot Best Practices?
Generate Spring Boot components following modern Java best practices and team conventions
Как установить скилл Spring Boot Best Practices?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Spring Boot Best Practices запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic