javajakarta-eeejbjboss-arquillianstateful-session-bean

Stateful bean doesn't keep state


I have a stateful bean:

@Stateful
public class ClientContext {

    private Band band;

    public Band getBand() {
        return band;
    }

    public void setBand(Band band) {
        this.band = band;
    }
}

I have Arquillian test.

public class RequestTest extends Arquillian {

    ...

    @Inject
    private ClientContext context;

    @Inject 
    private RequestProcessor processor;

    @Test
    public void test() {
        context.setBand(new Band());
        Assert.assertNotNull(context.getBand());

        processor.doSomething();
    }

}

And Processor code:

@Stateless
@LocalBean
public class RequestProcessor {

    ...

    @Inject
    private ClientContext context;

    public void doSomething() {
        System.out.println(context.getBand());
    }

}

I expect RequestProcessor to print out the Band. But actually I get null every time. What can be wrong or may be I don't understand Stateful beans correctly?


Solution

  • You are answering the question yourself, the main basis about the stateful is the keep just one instance per injection, which will live as long the injecting bean does. so in you need to share a state between beans, you could use a @SessionBean To clarify, the @Stateful means one instance are going to be created for each place where you are injecting it, this is useful when you need to bind some actions and their state to ONE component, so, if you need to create some info and then share between other classes you need to pick how you want to share it: @Singleton: There will be just one instance for the entire app. @SessionScoped: There will by one instance per client. @Stateless: Will create one if there is no other available, after it will be release for use of other clients If you are managing views the you can use too: @RequestScoped: Will create one instance for each request and then destroys it. @ViewScoped: The bean will remain as long the client keep making updates within the same view