spring-projects / spring-statemachine

Spring Statemachine is a framework for application developers to use state machine concepts with Spring.
1.55k stars 609 forks source link

How to construct state machine in a specified state #851

Open kvkboy opened 4 years ago

kvkboy commented 4 years ago

Now,I only use it

bookMachine.getStateMachineAccessor().withRegion().resetStateMachine(newDefaultStateMachineContext(BookState.LENT, null, null, null));

to reset state,so I want to know how do I create an machine with a specified status?

kvkboy commented 4 years ago

I've now built the library state machine, which has a lot of books.

 StateMachineBuilder.Builder<BookState, BookEvent> builder = StateMachineBuilder.builder();

        builder.configureConfiguration()
                .withConfiguration()
                .machineId("book")
                .beanFactory(beanFactory);

        builder.configureStates()
                .withStates()
                .initial(BookState.LENT)
                .states(EnumSet.allOf(BookState.class));

        builder.configureTransitions()
                .withExternal()
                .source(BookState.LENT).target(BookState.LOST)
                .event(BookEvent.LOST).action(action());

like this

image

For example, I have two books A and B both in Lent status. A Book uses the state machine, which causes the builder to become Lost status, since the builder is a bean of spring, it is a single ,A Book and B Book are sharing it, so then B Book uses the state machine is invalid because the builder is already in Lost status.

so How do I get B to use it successfully too?

hamid646m commented 4 years ago

State Machine is just a blueprint how States and Transition are defined. What you need to look into is call StateMachineContext, you can either store it to the database as byte array or you can build it on runtime based on some other meta data your save like State etc.

Have a look at org.springframework.statemachine.StateMachineContext

rustamzh commented 4 years ago

Each book would have its own state machine. To get a state machine use state machine factory. Docs