К основному содержанию
скилл CX Codex

spring-boot-dependency-injection — скилл для Claude Code

Скилл внедряет паттерны внедрения зависимостей через конструктор в Spring Boot. Он помогает избавиться от field injection и настроить выбор бинов через @Primary и @Qualifier.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-dependency-injection -a claude-code
Открыть на GitHub

Что делает spring-boot-dependency-injection

Скилл переводит сервисы и конфигурации Spring Boot на внедрение через конструктор с неизменяемыми полями final. Для обязательных зависимостей аннотация @Autowired опускается, если конструктор один. Необязательные компоненты оформляются через ObjectProvider или fallback-заглушки (no-op), чтобы код не падал из-за неожиданных null.

Логика связывания выносится из сервисов в классы @Configuration. Если типов несколько, по умолчанию ставится @Primary, а для именованных вариаций применяется @Qualifier. Скилл прямо запрещает маскировать циклические зависимости костылём @Lazy — это дефект архитектуры, требующий рефакторинга.

Проверка сборки контекста начинается с минимального теста @SpringBootTest в связке с @ContextConfiguration. Затем бизнес-логика тестируется обычными модульными тестами без поднятия контейнера Spring.

Какие задачи решает

  • перевести легаси-код с инъекции через поля на конструкторы
  • разрешить неоднозначность при нескольких бинах одного интерфейса
  • обработать опциональные интеграции без риска получить NullPointerException
  • настроить быстрое модульное тестирование сервисов без запуска Spring Context

Примеры запросов агенту

  • Отрефактори UserService: замени field injection на внедрение через конструктор и сделай поля final.
  • Добавь опциональный NotificationGateway в ReportService через ObjectProvider с no-op заглушкой.
  • Напиши минимальный тест загрузки контекста для PaymentConfiguration с несколькими бинами.

Как установить spring-boot-dependency-injection

1Через Skills CLI (Vercel)

npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-dependency-injection -a claude-code

2Вручную: положить файлы

~/.claude/skills/spring-boot-dependency-injection/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/spring-boot-dependency-injection/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о spring-boot-dependency-injection

Как установить spring-boot-dependency-injection в Claude Code?

Выполните команду npx skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-dependency-injection -a claude-code. Файл скилла запишется в ~/.claude/skills/spring-boot-dependency-injection/SKILL.md.

Зачем заменять внедрение зависимостей через поля на конструкторы?

Инъекция в поля прячет зависимости и усложняет модульное тестирование. Внедрение через конструктор позволяет передавать моки напрямую без создания контекста Spring.

Как скилл рекомендует обрабатывать циклические зависимости?

Он предостерегает от использования @Lazy для сокрытия циклов. Циклические зависимости рассматриваются как архитектурная ошибка, требующая пересмотра структуры классов.

Исходный текст

SKILL.md · MIT
---
name: spring-boot-dependency-injection
description: Provides dependency injection patterns for Spring Boot projects, including constructor-first design, optional collaborator handling, bean selection, and wiring validation. Use when creating services and configurations, replacing field injection, or troubleshooting ambiguous or fragile Spring wiring.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
---

# Spring Boot Dependency Injection

## Overview

Provides constructor-first dependency injection patterns for Spring Boot:
- mandatory collaborators via constructor injection
- optional collaborators via `ObjectProvider` or no-op fallbacks
- bean selection via `@Primary` and `@Qualifier`
- validation via minimal context tests before full integration

## When to Use

Use this skill when:
- creating a new `@Service`, `@Component`, `@Repository`, or `@Configuration` class
- replacing field injection in legacy Spring code
- resolving multiple beans of the same type with qualifiers or primary beans
- handling optional features, adapters, or integrations without null-driven wiring
- reviewing circular dependencies or brittle context startup failures
- preparing code for direct constructor-based unit testing


## Instructions

### 1. Separate mandatory and optional collaborators

For each class, identify:
- mandatory collaborators required for correct behavior
- optional collaborators that enable integrations, caching, notifications, or feature-flagged behavior

Mandatory collaborators belong in the constructor. Optional ones need an explicit strategy such as `ObjectProvider`, conditional beans, or a no-op implementation.

### 2. Default to constructor injection

For application services and adapters:
- inject mandatory dependencies through the constructor
- keep injected fields `final`
- instantiate the class directly in unit tests without starting Spring

A single constructor is usually enough; `@Autowired` is unnecessary in that case.

### 3. Resolve optional behavior intentionally

Good options include:
- `ObjectProvider<T>` when lazy access is useful
- `@ConditionalOnProperty` or `@ConditionalOnMissingBean` when wiring should change by configuration
- a no-op implementation when the caller should not care whether the feature is enabled

Avoid nullable collaborators that leave runtime behavior ambiguous.

### 4. Use bean selection annotations only when needed

When multiple beans share the same type:
- use `@Primary` for the default implementation
- use `@Qualifier` for named variants
- keep the qualifier names stable and easy to grep

If selection rules become complex, move them into a dedicated configuration class instead of spreading them across services.

### 5. Keep wiring in configuration, not business code

Use `@Configuration` and `@Bean` methods when:
- the object comes from a third-party library
- conditional creation logic is needed
- you need environment-specific wiring or explicit composition

Business services should not know how infrastructure collaborators are instantiated.

### 6. Validate wiring explicitly

After writing a new service or configuration:

1. **Verify the bean loads** with a minimal context test:
   ```java
   @SpringBootTest
   @ContextConfiguration(classes = UserService.class)
   class UserServiceWiringTest {
       @Autowired UserService userService;
       @Test void serviceIsInstantiated() { assertNotNull(userService); }
   }
   ```
2. **Run constructor-based unit tests** for service behavior (no Spring needed).
3. **Add slice tests** only when MVC, JPA, or messaging integration must be verified.
4. **Reserve `@SpringBootTest`** for container-wide wiring validation.

Failures at step 1 indicate wiring issues before business logic is added.

## Examples

### Example 1: Constructor-first application service

```java
@Service
public class UserService {

    private final UserRepository userRepository;
    private final EmailSender emailSender;

    public UserService(UserRepository userRepository, EmailSender emailSender) {
        this.userRepository = userRepository;
        this.emailSender = emailSender;
    }

    public User register(UserRegistrationRequest request) {
        User user = userRepository.save(User.from(request));
        emailSender.sendWelcome(user);
        return user;
    }
}
```

This class is easy to instantiate directly in a unit test with mocks.

### Example 2: Optional dependency with a no-op fallback

```java
@Service
public class ReportService {

    private final ReportRepository reportRepository;
    private final NotificationGateway notificationGateway;

    public ReportService(
        ReportRepository reportRepository,
        ObjectProvider<NotificationGateway> notificationGatewayProvider
    ) {
        this.reportRepository = reportRepository;
        this.notificationGateway = notificationGatewayProvider.getIfAvailable(NotificationGateway::noOp);
    }
}
```

This keeps optional behavior explicit without leaking `null` handling through the rest of the class.

### Example 3: Multiple beans with clear selection

```java
@Configuration
public class PaymentConfiguration {

    @Bean
    @Primary
    PaymentGateway stripeGateway() {
        return new StripePaymentGateway();
    }

    @Bean
    @Qualifier("fallbackGateway")
    PaymentGateway mockGateway() {
        return new MockPaymentGateway();
    }
}
```

Use `@Primary` for the default path and `@Qualifier` only where a specific variant is required.

## Best Practices

- Prefer constructor injection for mandatory dependencies.
- Keep service constructors small; if a class needs too many collaborators, the design probably wants another abstraction.
- Use no-op or conditional beans instead of nullable optional dependencies.
- Keep framework-specific creation logic in configuration classes.
- Test services without Spring first, then add container tests only where they add value.
- Remove field injection during refactors instead of extending it.

## Constraints and Warnings

- Field injection hides dependencies and makes tests harder to write.
- Circular dependencies are usually a design problem, not a wiring trick to solve with `@Lazy`.
- Overusing qualifiers can make the codebase hard to reason about; prefer better abstractions or clearer configuration.
- Optional collaborators still need deterministic behavior when absent.
- Full-context tests can hide the real source of wiring failures if used too early.

## References

- `references/reference.md`
- `references/examples.md`
- `references/spring-official-dependency-injection.md`

## Related Skills

- `spring-boot-crud-patterns`
- `spring-boot-rest-api-standards`
- `unit-test-service-layer`

© giuseppe-trisciuoglio · MIT · giuseppe-trisciuoglio/developer-kit

Похожие скиллы

Всё по теме «Бэкенд и API» →
spring-boot-engineer https://github.com/Jeffallan Разворачивает архитектуру Spring Boot 3.x, контроллеры, репозитории Spring Data JPA и правила Spring Security 6. Пригодится при сборке REST API, реактивных сервисов и микросервисов на Java. CX Codex +1 8 400установок spring-boot Mindrally Скилл задаёт агенту стиль кода на Spring Boot: REST-контроллеры, тесты, безопасность, сборка и деплой. Пригодится, когда проект на Java и хочется единообразия. CX Codex +1 832установок 302-frameworks-spring-boot-rest Juan Antonio Breña Moral Скилл для проектирования и разбора REST API на Spring Boot: методы, коды ответов, DTO, версионирование, пагинация, ошибки по RFC 7807. CX Codex +1 392установок 321-frameworks-spring-boot-testing-unit-tests Juan Antonio Breña Moral Скилл ведёт агента по юнит-тестам Spring Boot: Mockito без поднятия контекста, срезы для контроллеров, параметризованные тесты. Пригодится, когда в проекте расплодились @SpringBootTest. CX Codex +1 387установок spring-boot-patterns decebals Скилл задаёт структуру Spring Boot-проекта и шаблоны для контроллеров, сервисов и репозиториев. Пригодится, когда агент пишет новый код или разбирает чужой. CX Codex +1 322установок java-spring-boot pluginagentmarketplace Скилл помогает создавать бэкенд на Spring Boot 3: настраивать REST API, аутентификацию через Spring Security, доступ к базам через Spring Data и мониторинг Actuator. CX Codex +1 11 800установок

Из того же набора93

unit-test-json-serialization Скилл подсказывает, как писать юнит-тесты сериализации и десериализации JSON на Jackson и @JsonTest в Spring Boot. CX Codex +1 3 800установок unit-test-controller-layer Генерирует модульные тесты для REST-контроллеров Spring через MockMvc и Mockito. Пригодится для быстрой проверки HTTP-статусов, валидации и JsonPath без запуска полного контекста. CX Codex +1 3 800установок unit-test-parameterized Скилл для параметризованных тестов на JUnit 5: один метод гоняет много входных значений. Пригодится, когда надо покрыть граничные случаи без копипасты. CX Codex +1 3 800установок nextjs-authentication Скилл даёт готовые шаблоны аутентификации для Next.js 15+ App Router на Auth.js 5: провайдеры, защита маршрутов, сессии и роли. CX Codex +1 3 800установок nextjs-code-review Проверяет код Next.js перед слиянием изменений: компоненты, серверные действия, кэш и маршруты. Пригодится после новой функции или миграции. CX Codex +1 3 800установок unit-test-wiremock-rest-api Скилл задаёт шаблоны юнит-тестов внешних REST API на WireMock: заглушки ответов, проверка запросов, имитация сбоев без реальной сети. CX Codex +1 3 800установок spring-boot-actuator Скилл помогает настроить Spring Boot Actuator: добавить пробы жизнеспособности для оркестраторов, защитить служебные эндпоинты и экспортировать метрики Micrometer в Prometheus. CX Codex +1 3 800установок spring-ai-mcp-server-patterns Скилл с шаблонами MCP-серверов на Spring Boot и Spring AI: инструменты через @Tool, промпт-шаблоны, транспорты stdio, HTTP и SSE. CX Codex +1 3 800установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой