Can an EJB3 bean “self inject” and call its own methods via EJB container?

别来无恙 提交于 2019-12-03 11:39:04

Update: As noted by other answers, this is indeed technically possible. Please see the answers of Csaba and Michael on how and why it works despite the apparend endless recursion.


I cannot give a 100% accurate answer but I'm pretty sure that this is not possible.

I think so because for injecting the Foo bean into the Foo bean itself the container would initially have to create a Foo instance which he can inject afterwards. But to create this he has to inject an already existing instance of Foo into the Foo to be created... which leads to an infinite recursion.

If you need separate transactions I'd suggest to keep things easy and create two independend beans/interfaces.

Self injection of a EJB is indeed possible. The reason why an infinite recursion won't happen in this case is pretty simple: the container doesn't inject an actual bean instance from the pool. Instead, it injects a proxy object. When you call a method on the injected proxy (foo), the container gets a bean instance from its pool or creates one, if there are no available instances.

It is possible to do a self injection. You need to use SessionContext.

SessionContext sc = ...
sc.getBusinessObject(FooBean.class).processWithNewTransaction()

I'd tend to disagree, often it's useful for transaction management to call a local bean method via the container.

Exactly as the example if you had to call a local bean method inside a loop you'd be better having a transaction per iteration than for all iterations. (provided business logic wasn't "all or nothing" like despatching a delivery, or issuing stock)

Interesting question. I never create a method with a different transaction attribute in the same bean, that is, this begs for refactoring. This usually makes it hard to spot bugs in the application when it evolves.

EDIT: fixed typos

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!