티스토리 뷰

카테고리 없음

EnableWithStateMachine 소개

행복[HappY] 2025. 3. 7. 17:55

@EnableWithStateMachine은 Spring State Machine에서 사용되는 애너테이션입니다. Spring State Machine은 복잡한 상태 전이(state transition)를 다루기 위한 프레임워크로, 특정 이벤트에 따라 상태가 변경되는 워크플로우를 쉽게 구현할 수 있도록 도와줍니다.

 

 

 

@EnableWithStateMachine의 역할

Spring State Machine을 사용할 때, 상태 머신(State Machine)을 활성화하기 위해 @EnableStateMachine 또는 @EnableStateMachineFactory 애너테이션을 사용합니다. 그런데, @EnableWithStateMachine 애너테이션은 특정 StateMachine 빈과 함께 사용할 수 있도록 해주는 기능을 합니다.

 

주요 기능

  1. StateMachine 활성화
    해당 애너테이션을 사용하면 Spring이 자동으로 상태 머신을 감지하고 관리할 수 있도록 설정합니다.
  2. 특정 빈과 연결 가능
    특정 StateMachine을 특정 빈에 연결하여 사용할 수 있도록 합니다. 이를 통해 하나의 애플리케이션에서 여러 개의 상태 머신을 다룰 수 있습니다.
  3. 상태 변화 감지 및 핸들링
    @OnTransition, @OnTransitionStart, @OnTransitionEnd 등의 애너테이션과 함께 사용하여 상태 변화 이벤트를 처리할 수 있습니다.

 

 

 

사용 예시

Spring State Machine을 구성하는 기본적인 예제를 살펴보겠습니다.

 

1. 상태와 이벤트 정의

public enum States {
    STATE1, STATE2
}

public enum Events {
    EVENT1, EVENT2
}

 

2. 상태 머신 구성

@Configuration
@EnableStateMachine
public class StateMachineConfig extends StateMachineConfigurerAdapter<States, Events> {
    
    @Override
    public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception {
        states
            .withStates()
            .initial(States.STATE1)
            .state(States.STATE2);
    }
    
    @Override
    public void configure(StateMachineTransitionConfigurer<States, Events> transitions) throws Exception {
        transitions
            .withExternal()
            .source(States.STATE1).target(States.STATE2).event(Events.EVENT1);
    }
}

 

3. 상태 변화 감지 (@WithStateMachine 활용)

@Component
@WithStateMachine
public class StateMachineEventListener {

    @OnTransition(source = "STATE1", target = "STATE2")
    public void onTransition() {
        System.out.println("STATE1 -> STATE2 전환됨");
    }
}

 

 

 

@EnableWithStateMachine과 @WithStateMachine 차이점

  • @EnableWithStateMachine
    상태 머신을 활성화하는 역할을 하며, 상태 머신의 구성을 설정하는 클래스에 사용됩니다.
  • @WithStateMachine
    특정 상태 머신과 연결된 컴포넌트에서 상태 변화를 감지하고 핸들링할 수 있도록 하는 애너테이션입니다.

 

 

 

요약

  • @EnableWithStateMachine은 Spring State Machine을 활성화하고 상태 머신을 사용할 수 있도록 설정하는 애너테이션입니다.
  • 상태 머신의 동작을 정의하는 클래스에 주로 사용됩니다.
  • @WithStateMachine과 함께 사용하여 상태 변화 이벤트를 처리할 수 있습니다.

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
글 보관함