简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM