質問

I have an EJB Stateless Session Bean. I have these requirements:

  1. This Stateless EJB should be initialized at startup
  2. The initialization code should make a transactional access to a database

The problem is:

  1. @Startup is only available for @Singleton EJBs
  2. @PostConstruct annotation (at least on Websphere) doesn't have a transactional context at this point so the initialization code explode here!

Possible solutions?

  1. Use a Java EE Timer but it seems to be designed for periodic execution. I want just only one execution at time zero.
  2. Use a @Singleton + @Startup EJB just for initialization purposes and inject this singleton EJB to the dependant Stateless EJBs.

Question:

  1. Can any one explain how it is supposed a Stateless EJB to be initialized? or it has no sense? (I mean, stateless EJB are supposed to not to have initialization state?)
  2. Is there any pattern out there that says use of secondary EJB @Singleton with @Startup is a good idea?
役に立ちましたか?

解決

Finally i opted for:

  • EJB @Stateless -- having a reference to --> EJB @Singleton (with @Startup)

That way, i can initialize the (shared and readonly) state or context necessary to serve requests.

他のヒント

Initializing a stateless EJB has no sense since this is the job of the Java EE container. Moreover, Java EE 6 provides the IOC pattern natively. IOC basically means hiding injected resources initialization process.

Your 2. solution is correct, as you need a transactional access.

Then you need to consider both cases/states :

a. singleton started up correcty

b. singleton failed at startup

In other words, are you sure that your (1.) statement is correct or you may interpret it with a lazy-init pattern ?

As the @startup occurs when application startup, maybe a state on the singleton with a lazy init activation is also matching to your needs?

The initialization code should make a transactional access to a database.

It is not clear to me for what the database access is, but in case you need fetch some data and store it as attributes of your stateless seasion bean, take in mind the following:

  • this information will be replicated in every stateless instance.

  • you will execute a database query every time a new bean instance is created.

  • at some point, it could be hard to be sure that all your beans instances have the same state.

I don't know the name of the pattern, but store the information in a Singleton session bean and inject it inside a stateless its a good solution. Even the Singleton bean can manage simultaneos requests, therefore, it won't become a bottleneck. It also allows you to manage possible information changes in a more consistent way.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top