-->

Injecting RequestScoped CDI Bean into ApplicationS

2020-07-25 05:02发布

问题:

This article explains that you can inject RequestScoped beans into ApplicationScoped beans and the client proxy will point to the correct instance during a request: Bean instance of a shorter scope injected in a bean instance of a larger scope in CDI - how does it work?

How does this work when using a separate producer class that does some extra processing and produces the RequestScoped bean? Upon deployment to the application server I get a DeploymentException due to ambiguous dependencies since both the managed bean and my producer method are eligible.

回答1:

Indeed, it works. In such case CDI impl just executes your @Produces method whenever needed.

You got your exception because CDI searches for beans by type and your have two definitions of the same type. So if you have declared already bean with @Produces you cannot let CDI to have exactly the same bean definition available on the classpath.

Following example is invalid:

@ApplicationScoped
public class SomeFactory {

    @Produces
    public SomeBean produceSome() {
        return new SomeBean();
    }
}

@RequestScoped   // bug, redundant definition
public class SomeBean {
}

Ps. Details also depend on the actual value of the bean-discovery-mode.

You can look also at this sample SO answer.

Personally, I'm not a fan of auto-discovery and classpath scanning - but this concept lies at the foundation of the CDI and Java EE. That's one of the reasons I usually don't recommend people Java EE servers.