Spring Boot Patterns logo

Spring Boot Patterns

Community
j4flmao
spring-boot-patterns

Use this skill when implementing Spring Boot patterns — dependency injection, AOP, repository patterns, security configuration, testing patterns, transaction management. This skill enforces: constructor injection (no @Autowired on fields), @Transactional at service layer, AOP for cross-cutting concerns, repository abstraction with Spring Data, slice tests with TestContainers. Do NOT use for: Spring Boot project structure (see architecture skill), non-Spring Java, frontend.

Overview

Publisherj4flmao
Repositoryagent-skills
Skill namespring-boot-patterns
Stars
41
Forks
6
Bundled files
6
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 6 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by j4flmao on GitHub. Read the source before you install it.

Installation

Install the Spring Boot Patterns AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/spring-boot/patterns
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/spring-boot/patterns .claude/skills/spring-boot-patterns
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Spring Boot Patterns in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Spring Boot Patterns on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Spring Boot Patterns is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Spring Boot Patterns

Purpose

Implement production-grade Spring Boot patterns — dependency injection, aspect-oriented programming, data access, security, transaction management, and testing.

Architecture Decision Trees

Injection Strategy

CriterionConstructorField (@Autowired)Setter
ImmutabilityYes (final fields)NoNo
TestabilityInstantiate directlyReflection requiredEasy override
Null safetyCompiler-enforcedRuntime NPE if missingRuntime NPE
Circular dependencyDetected at startupHiddenHidden
Constructor paramsAll in one callZero-arg constructor neededMutable
Framework couplingNone (pure Java)Spring annotationSpring annotation

Decision: Constructor injection always. Field injection only in tests (via @InjectMocks). Setter injection never.

Transaction Propagation

PropagationBehaviorUse Case
REQUIRED (default)Join existing or create newMost service methods
REQUIRES_NEWSuspend existing, create newAudit logging, independent actions
NESTEDSavepoint within existingPartial rollback within batch
MANDATORYFail if no existing txInternal service calls that need caller tx
NEVERFail if existing txLong-running reads, avoid connection hold
SUPPORTSOptional txRead-only queries, optional transactional
NOT_SUPPORTEDSuspend existingBackground tasks, after-commit actions

Decision: REQUIRED for write operations. REQUIRES_NEW for audit/events. Read-only SUPPORTS.

Testing Slice Strategy

AnnotationScopeWhat's MockedWhat's Real
@SpringBootTestFull appNothing (full context)Everything
@WebMvcTestWeb layer onlyService layerControllers, filters
@DataJpaTestJPA onlyNothingRepositories, entities
@JsonTestJSON onlyNothingJSON serialization
@RestClientTestREST clientServerRestTemplate/WebClient
@DataRedisTestRedisNothingRedis repos

Decision: @WebMvcTest for controller tests. @DataJpaTest for repository tests. @SpringBootTest for integration/E2E only.

Agent Protocol

Trigger

User request includes: Spring Boot patterns, Spring design patterns, dependency injection Spring, AOP, Spring Data, Spring Security, transaction management, Spring Testing, @Transactional, @Autowired, TestContainers, WireMock, @DataJpaTest, @WebMvcTest.

Input Context

  • Spring Boot version (3.x preferred)
  • Data access (Spring Data JPA, JDBC, R2DBC)
  • Security (Spring Security, OAuth2, JWT)
  • Testing framework (JUnit 5, Mockito, TestContainers)
  • Architecture (package-by-feature, hexagonal)

Output Artifact

Pattern implementations with code examples, configuration snippets, testing strategies.

Response Format

Produce artifact directly. No preamble, no postamble, no explanations. No filler, no hedging, no transitions. Strip articles a/an/the where unambiguous. Compress output — why use many token when few do trick.

Completion Criteria

  • DI pattern with constructor injection and qualifiers
  • AOP aspect for logging/performance/timing
  • Repository pattern with Spring Data
  • Security chain with JWT or OAuth2
  • Transaction propagation and isolation configured
  • Test slices for unit, integration, and E2E

Max Response Length

4096 tokens

Workflow

Step 1: Constructor Injection Pattern

java
// CORRECT: Constructor injection with required dependencies
@Service
public class OrderService {
    private final OrderRepository orderRepository;
    private final InventoryClient inventoryClient;
    private final EventPublisher eventPublisher;

    public OrderService(
        OrderRepository orderRepository,
        @Qualifier("cachingClient") InventoryClient inventoryClient,
        EventPublisher eventPublisher
    ) {
        this.orderRepository = orderRepository;
        this.inventoryClient = inventoryClient;
        this.eventPublisher = eventPublisher;
    }
}

// WRONG: Field injection — never do this
@Service
public class OrderService {
    @Autowired private OrderRepository orderRepository;  // NO
    @Autowired private InventoryClient inventoryClient;  // NO
}

// WRONG: Setter injection — avoid
@Service
public class OrderService {
    private OrderRepository orderRepository;

    @Autowired  // NO — use constructor
    public void setOrderRepository(OrderRepository repo) {
        this.orderRepository = repo;
    }
}

Step 2: Interface Segregation for Dependencies

java
// Define narrow interfaces — one responsibility each
public interface OrderRepository {
    Optional<Order> findById(OrderId id);
    Page<Order> findByCustomerId(String customerId, Pageable pageable);
    Order save(Order order);
    void deleteById(OrderId id);
}

public interface InventoryClient {
    boolean checkAvailability(String sku, int quantity);
    int reserveStock(String sku, int quantity);
    void releaseStock(String sku, int quantity);
}

public interface EventPublisher {
    void publish(DomainEvent event);
}

// Implementation with qualifier
@Component
@Qualifier("cachingClient")
public class CachingInventoryClient implements InventoryClient {
    private final InventoryClient delegate;
    private final CacheManager cache;

    public CachingInventoryClient(InventoryClient delegate, CacheManager cache) {
        this.delegate = delegate;
        this.cache = cache;
    }

    @Override
    public boolean checkAvailability(String sku, int quantity) {
        return cache.get(sku, () -> delegate.checkAvailability(sku, quantity));
    }
}

Step 3: AOP for Cross-Cutting Concerns

java
@Aspect
@Component
public class LoggingAspect {
    private static final Logger log = LoggerFactory.getLogger(LoggingAspect.class);

    @Around("execution(* com.project..*(..)) && @annotation(LogExecution)")
    public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.nanoTime();
        Object result = joinPoint.proceed();
        long duration = System.nanoTime() - start;
        log.info("{} executed in {}ms",
            joinPoint.getSignature().toShortString(),
            TimeUnit.NANOSECONDS.toMillis(duration));
        return result;
    }

    @AfterThrowing(
        pointcut = "execution(* com.project.*.application.*.*(..))",
        throwing = "ex"
    )
    public void logApplicationException(JoinPoint joinPoint, RuntimeException ex) {
        log.error("Application exception in {}: {}",
            joinPoint.getSignature().toShortString(), ex.getMessage());
    }
}

// Custom annotation
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecution {}

Step 4: Repository Pattern

java
// Domain port (in domain package — zero Spring imports)
public interface OrderRepository {
    Optional<Order> findById(OrderId id);
    Order save(Order order);
    void delete(OrderId id);
}

// Spring Data JPA adapter (in infrastructure)
@Component
public class SpringDataOrderRepository implements OrderRepository {
    private final JpaOrderRepository jpaRepo;

    public SpringDataOrderRepository(JpaOrderRepository jpaRepo) {
        this.jpaRepo = jpaRepo;
    }

    @Override
    public Optional<Order> findById(OrderId id) {
        return jpaRepo.findById(id.getValue())
            .map(OrderJpaEntity::asDomain);
    }

    @Override
    @Transactional
    public Order save(Order order) {
        OrderJpaEntity entity = OrderJpaEntity.fromDomain(order);
        return jpaRepo.save(entity).asDomain();
    }
}

// Spring Data interface (internal to infrastructure)
interface JpaOrderRepository extends JpaRepository<OrderJpaEntity, String> {
    Page<OrderJpaEntity> findByCustomerId(String customerId, Pageable pageable);
    Optional<OrderJpaEntity> findByOrderNumber(String orderNumber);
}

Step 5: Transaction Management

java
@Service
public class PaymentService {
    private final PaymentGateway gateway;
    private final PaymentRepository paymentRepo;
    private final OrderRepository orderRepo;

    public PaymentService(
        PaymentGateway gateway,
        PaymentRepository paymentRepo,
        OrderRepository orderRepo
    ) {
        this.gateway = gateway;
        this.paymentRepo = paymentRepo;
        this.orderRepo = orderRepo;
    }

    @Transactional(rollbackFor = PaymentException.class)
    public PaymentResult processPayment(ProcessPaymentCommand command) {
        // 1. Validate order
        Order order = orderRepo.findById(command.orderId())
            .orElseThrow(() -> new OrderNotFoundException(command.orderId()));

        // 2. Charge payment gateway
        PaymentCharge charge = gateway.charge(
            command.amount(),
            command.paymentToken()
        );

        // 3. Save payment record
        Payment payment = Payment.create(command.orderId(), charge.transactionId(), command.amount());
        paymentRepo.save(payment);

        // 4. Update order status
        order.markAsPaid();
        orderRepo.save(order);

        return new PaymentResult(payment.getId(), charge.transactionId());
    }
}

Step 6: Security Configuration

java
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
    private final JwtTokenProvider tokenProvider;
    private final UserDetailsService userDetailsService;

    public SecurityConfig(JwtTokenProvider tokenProvider, UserDetailsService userDetailsService) {
        this.tokenProvider = tokenProvider;
        this.userDetailsService = userDetailsService;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(AbstractHttpConfigurer::disable)
            .sessionManagement(session ->
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/v1/auth/**", "/actuator/health").permitAll()
                .requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .authenticationProvider(authenticationProvider())
            .addFilterBefore(
                new JwtAuthenticationFilter(tokenProvider, userDetailsService),
                UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);
        provider.setPasswordEncoder(passwordEncoder());
        return provider;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Step 7: Event-Driven Pattern

java
// Domain event
public record OrderSubmittedEvent(OrderId orderId, String customerId, Money total) implements DomainEvent {}

// Publisher
@Component
public class SpringEventPublisher implements EventPublisher {
    private final ApplicationEventPublisher publisher;

    public SpringEventPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    @Override
    public void publish(DomainEvent event) {
        publisher.publishEvent(event);
    }
}

// Listener
@Component
public class OrderSubmittedHandler {
    private final EmailService emailService;
    private final InventoryService inventoryService;

    public OrderSubmittedHandler(EmailService emailService, InventoryService inventoryService) {
        this.emailService = emailService;
        this.inventoryService = inventoryService;
    }

    @EventListener
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void handleOrderSubmitted(OrderSubmittedEvent event) {
        emailService.sendOrderConfirmation(event.orderId(), event.customerId());
        inventoryService.reserveItems(event.orderId());
    }
}

// Async event processing
@Configuration
@EnableAsync
public class AsyncConfig {
    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("async-");
        executor.initialize();
        return executor;
    }
}

@Component
public class AsyncOrderHandler {
    @EventListener
    @Async
    public void handle(OrderSubmittedEvent event) {
        // Long-running task runs on thread pool
    }
}

Production Considerations

Performance

  • Connection pool: spring.datasource.hikari.maximum-pool-size=20 (adjust per concurrent users)
  • JPA: spring.jpa.open-in-view=false (prevents lazy init exceptions in views, forces explicit fetch planning)
  • Caching: Spring Cache with Caffeine for local, Redis for distributed; annotate methods with @Cacheable
  • Async: @Async with custom ThreadPoolTaskExecutor (corePoolSize=10, maxPoolSize=50)
  • Logging: logback-spring.xml with structured JSON appender; async appender for high-throughput
  • Graceful shutdown: server.shutdown=graceful + spring.lifecycle.timeout-per-shutdown-phase=30s

Observability

  • Actuator: expose /actuator/health, /actuator/metrics, /actuator/prometheus (secured behind management port)
  • Metrics: Micrometer with MicrometerRegistry; custom metrics via MeterRegistry bean
  • Tracing: Micrometer Tracing with Brave + Zipkin for distributed tracing
  • Health indicators: custom HealthIndicator for external services (DB, Redis, Kafka, downstream APIs)

Common Pitfalls

  • N+1 query: use @EntityGraph or JOIN FETCH in JPQL; enable hibernate.query.fail_on_pagination_over_collection_fetch
  • Lazy loading exceptions: disable open-in-view, plan fetches explicitly
  • @Transactional on private methods: Spring proxies can't intercept private calls — move to public or use self-injection

Anti-Patterns

Anti-PatternWhyFix
@Autowired on fieldsCan't test without Spring; hidden depsConstructor injection
@Transactional in controllersTransaction spans HTTP response; connection heldService-layer only
@DataJpaTest with full contextSlow test startupUse slice annotations
@SpringBootTest for every testSlow CI; tests depend on full contextSlice tests per concern
Catch-all @ComponentScanSlow startup; unexpected beans picked upExplicit configuration with @Enable...
Giant application.propertiesHard to maintain; no type safetyType-safe @ConfigurationProperties per module
Using @Query with string concatenationSQL injection riskUse @Param + named parameters or Specification
@Async without custom executorDefault SimpleAsyncTaskExecutor creates unlimited threadsDefine ThreadPoolTaskExecutor bean
Service calling service directly (no interface)Tight coupling; can't proxy for tx/AOPDefine interface, proxy will apply cross-cutting

Rules

  • references/spring-boot-data-access.md — Spring Boot Data Access Reference
  • references/spring-boot-deployment.md — Spring Boot Deployment
  • references/spring-boot-observability.md — Spring Boot Observability
  • references/spring-boot-security.md — Spring Boot Security Reference
  • references/spring-patterns.md — Spring Patterns
  • references/spring-testing.md — Spring Testing

Handoff

Hand off to backend/spring-boot/architecture/SKILL.md for project structure or backend/universal/testing/SKILL.md for broader testing patterns.

References

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Spring Boot Patterns AI skill do?

Use this skill when implementing Spring Boot patterns — dependency injection, AOP, repository patterns, security configuration, testing patterns, transaction management. This skill enforces: constructor injection (no @Autowired on fields), @Transactional at service layer, AOP for cross-cutting concerns, repository abstraction with Spring Data, slice tests with TestContainers. Do NOT use for: Spring Boot project structure (see architecture skill), non-Spring Java, frontend.

Why use Spring Boot Patterns on TypingMind?

Because you install it once and use it with any model. Spring Boot Patterns is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Spring Boot Patterns in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/j4flmao/agent-skills/tree/main/skills/backend/spring-boot/patterns. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Spring Boot Patterns?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Spring Boot Patterns?

As many as you like. As long as a model supports skills, you can use Spring Boot Patterns with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Spring Boot Patterns AI skill free?

Yes. It is published on GitHub by j4flmao under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇