CDI with unmanaged objects

Suppose I have two classes: first a class without any properties, fields or annotations:

public class B {} 

And the class that B introduces is like this:

 public class A { @Inject private B b; public B getB() { return b; } } 

Now class A is pretty useless until we use it, so there are two options:

  • @ Paste it
  • Create it manually using the robust "new A ()"

If A receives an injection, the CDI controls it and is kind enough to introduce B, which has an implicit @Dependent scope. Cool, just what I want.

However, if I manually build A (say, in a factory or builder), CDI completely ignores my object and will not introduce an object of type B.

Example: I am talking about when this does not work, here the object a will always remain zero:

 public class Builder { @Inject private A a; public static Builder ofTypeSomething() { // do some magic here return new Builder(); } private Builder() { // and some more here } } 

Why is this not working?

Class A is a valid managed bean and has a valid scope, like class B. Even if I add @Producer to a static method, it will not change anything (this is good, because the idea of ​​a static method is to call it, and not insert Builder in any location).

+7
source share
1 answer

Injection injection, although useful, is not magical. The DI method is that when you request a container for an instance of an object, the container first constructs it (via new() ) and then sets the dependencies (how this happens depends on your structure).

If you create an object yourself, the container has no idea that you created the object and cannot establish the dependencies of the object.

If you want to use a factory, then most frameworks have some way of setting up the object so that the container knows to make a static call to the factory method and not call the constructor of the object. However, you should still get your entity from the container.

Edit: This site shows how to use factory in CDI.

+9
source

All Articles