spring-statemachine
Spring Statemachine for building finite state machine applications. Covers states, transitions, guards, actions, persistence, and hierarchical states. USE WHEN: user mentions "spring statemachine", "state machine Spring", "workflow Spring", "finite state machine", "order state", "document lifecycle", "guards actions transitions" DO NOT USE FOR: simple status flags - use enum fields, complex workflow orchestration - use `spring-integration` or Camunda, business rules engine - use Drools
What this skill does
# Spring Statemachine - Quick Reference
> **Full Reference**: See [advanced.md](advanced.md) for @WithStateMachine annotation, hierarchical states, choice pseudostates, timer transitions, listeners, persistence, and testing.
> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `spring-statemachine` for comprehensive documentation.
## Dependencies
```xml
<!-- Spring Statemachine 4.0+ for Spring Boot 3.x -->
<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-starter</artifactId>
<version>4.0.0</version>
</dependency>
<!-- For persistence -->
<dependency>
<groupId>org.springframework.statemachine</groupId>
<artifactId>spring-statemachine-data-jpa</artifactId>
<version>4.0.0</version>
</dependency>
```
## Core Concepts
```
┌─────────────────────────────────────────────────────────────┐
│ State Machine │
│ │
│ ┌──────────┐ EVENT_A ┌──────────┐ │
│ │ STATE_1 │ ─────────────▶ │ STATE_2 │ │
│ │ (initial)│ │ │ │
│ └──────────┘ └────┬─────┘ │
│ │ │
│ EVENT_B │
│ │ │
│ ▼ │
│ ┌──────────┐ │
│ │ STATE_3 │ │
│ │ (final) │ │
│ └──────────┘ │
└─────────────────────────────────────────────────────────────┘
```
## Basic Configuration
### States and Events
```java
public enum OrderStates {
CREATED,
PENDING_PAYMENT,
PAID,
PROCESSING,
SHIPPED,
DELIVERED,
CANCELLED,
REFUNDED
}
public enum OrderEvents {
SUBMIT,
PAY,
PROCESS,
SHIP,
DELIVER,
CANCEL,
REFUND
}
```
### State Machine Configuration
```java
@Configuration
@EnableStateMachineFactory
public class OrderStateMachineConfig
extends EnumStateMachineConfigurerAdapter<OrderStates, OrderEvents> {
@Override
public void configure(StateMachineStateConfigurer<OrderStates, OrderEvents> states)
throws Exception {
states
.withStates()
.initial(OrderStates.CREATED)
.state(OrderStates.PENDING_PAYMENT)
.state(OrderStates.PAID)
.state(OrderStates.PROCESSING)
.state(OrderStates.SHIPPED)
.end(OrderStates.DELIVERED)
.end(OrderStates.CANCELLED)
.end(OrderStates.REFUNDED);
}
@Override
public void configure(StateMachineTransitionConfigurer<OrderStates, OrderEvents> transitions)
throws Exception {
transitions
.withExternal()
.source(OrderStates.CREATED)
.target(OrderStates.PENDING_PAYMENT)
.event(OrderEvents.SUBMIT)
.and()
.withExternal()
.source(OrderStates.PENDING_PAYMENT)
.target(OrderStates.PAID)
.event(OrderEvents.PAY)
.guard(paymentValidGuard())
.action(paymentAction())
.and()
.withExternal()
.source(OrderStates.PAID)
.target(OrderStates.PROCESSING)
.event(OrderEvents.PROCESS)
.and()
.withExternal()
.source(OrderStates.PROCESSING)
.target(OrderStates.SHIPPED)
.event(OrderEvents.SHIP)
.action(shipAction())
.and()
.withExternal()
.source(OrderStates.SHIPPED)
.target(OrderStates.DELIVERED)
.event(OrderEvents.DELIVER)
.and()
// Cancel from multiple states
.withExternal()
.source(OrderStates.CREATED)
.target(OrderStates.CANCELLED)
.event(OrderEvents.CANCEL)
.and()
.withExternal()
.source(OrderStates.PENDING_PAYMENT)
.target(OrderStates.CANCELLED)
.event(OrderEvents.CANCEL);
}
}
```
---
## Guards and Actions
### Guards (Conditions)
```java
@Configuration
public class OrderGuards {
@Bean
public Guard<OrderStates, OrderEvents> paymentValidGuard() {
return context -> {
Order order = (Order) context.getExtendedState()
.getVariables().get("order");
PaymentInfo payment = (PaymentInfo) context.getMessage()
.getHeaders().get("payment");
return payment != null &&
payment.getAmount().compareTo(order.getTotal()) >= 0;
};
}
@Bean
public Guard<OrderStates, OrderEvents> refundEligibleGuard() {
return context -> {
Order order = (Order) context.getExtendedState()
.getVariables().get("order");
LocalDateTime deliveredAt = order.getDeliveredAt();
// Refund within 30 days
return deliveredAt != null &&
deliveredAt.plusDays(30).isAfter(LocalDateTime.now());
};
}
}
```
### Actions
```java
@Configuration
public class OrderActions {
@Bean
public Action<OrderStates, OrderEvents> paymentAction() {
return context -> {
Order order = (Order) context.getExtendedState()
.getVariables().get("order");
PaymentInfo payment = (PaymentInfo) context.getMessage()
.getHeaders().get("payment");
order.setPaymentId(payment.getTransactionId());
order.setPaidAt(LocalDateTime.now());
orderRepository.save(order);
log.info("Payment processed for order: {}", order.getId());
};
}
@Bean
public Action<OrderStates, OrderEvents> shipAction() {
return context -> {
Order order = (Order) context.getExtendedState()
.getVariables().get("order");
String trackingNumber = shippingService.createShipment(order);
order.setTrackingNumber(trackingNumber);
order.setShippedAt(LocalDateTime.now());
orderRepository.save(order);
notificationService.sendShippingNotification(order);
};
}
// Error action
@Bean
public Action<OrderStates, OrderEvents> errorAction() {
return context -> {
Exception exception = context.getException();
log.error("State machine error: {}", exception.getMessage());
};
}
}
```
---
## State Machine Service
```java
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderStateMachineService {
private final StateMachineFactory<OrderStates, OrderEvents> factory;
private final OrderRepository orderRepository;
public void processEvent(Long orderId, OrderEvents event, Map<String, Object> headers) {
Order order = orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
StateMachine<OrderStates, OrderEvents> sm = build(order);
Message<OrderEvents> message = MessageBuilder
.withPayload(event)
.copyHeaders(headers)
.setHeader("orderId", orderId)
.build();
// Reactive event sending (Spring Statemachine 4.0+)
sm.sendEvent(Mono.just(message))
.doOnComplete(() -> log.info("Event {} processed for order {}", event, orderId))
.doOnError(e -> log.error("Error processing event: {}", e.getMessage()))
.subscribe();
}
private StateMachiRelated in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.