Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular dependencies between stateless session beans - good practice?

I just ran into a deployment error when deploying two stateless session beans each with dependency to the other and using @Inject.

@Stateless
class BeanA {
    @Inject 
    BeanB b;

    public void doSomething() {
        b.doSomething();
    }
}

@Stateless
class BeanB {
    @Inject
    BeanA a;

    public void doSomeOtherThing() {
        a.doSomeOtherThing();
    }
}

When deploying this, I get this exception from Glassfish / weld:

org.jboss.weld.exceptions.DeploymentException: WELD-001443 Pseudo scoped bean has circular dependencies.

Injecting the Beans with @EJB instead of @Inject, everything works fine. Now I have two questions.

First - what happens inside weld that this won't be allowed?

Second (probably more important) - is this bad practice on architectural side and if yes do you know any patterns to avoid it? From my current knowledge was that business driven services on the same layer are allowed to communicate with each other in any way they need.

like image 674
peez80 Avatar asked Jul 21 '26 17:07

peez80


1 Answers

As written in the spec

The container is not required to support circular chains of dependencies where every bean participating in the chain has a pseudo-scope.

Here, you didn't add scope annotation to your session beans so they have the default scope @Dependent. Dependent being a pseudo-scope, it's normal to have this error.

To solve this, add @ApplicationScoped to at least one of your bean. In fact it's a good practice to put your stateless session bean in application context, it prevents CDI to recreate its proxy around the existing EJB each time you inject it.

Regarding circularities, it's not a bad practice, but should be used only when needed since it can bring more complexity to understand your app, debug it and prevent these kind of errors.

like image 135
Antoine Sabot-Durand Avatar answered Jul 24 '26 08:07

Antoine Sabot-Durand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!