4

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.

Community
  • 1
  • 1
phivo
  • 183
  • 2
  • 16
  • I'm getting rid of my producer classes and do my additional processing directly in my RequestScoped Bean. This seems a better approach so everything is in one place and not distributed across two classes. – phivo Feb 25 '16 at 10:35

1 Answers1

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.

Community
  • 1
  • 1
G. Demecki
  • 10,145
  • 3
  • 58
  • 58
  • Ok, so the only solution is with a custom qualifier. We used this approach in the past when we injected a String. So I'd rather go for getting rid of the producer completely. Thanks for the clarification! – phivo Feb 26 '16 at 13:09
  • You are welcome. Ps. to be clear, custom qualifier isn't the only solution. Alternative is a `bean-discovery-mode="annotated"` + removal from all beans, for which you have Producers methods, any "bean defining annotations". – G. Demecki Feb 26 '16 at 13:45