nicolasst22
nicolasst22

Reputation: 99

Dependency Injection... Basic Basic (not injection when new instance)

When I create a new instance by

MyObject obj = new MyObject();

the injections never happen.

The example source for MyObject could be...

@Stateless
public class MyObject{

    @Inject
    Injection inj;

    public MyObject() {
    }
    ...
}

do the injections just work in injected objects? Is there no way of the using injection when I explicitly create a new instance?

I want to create a Class menu that creates instances dynamically (using reflection... the reflection is not the problem... I have tried using the new syntax).

I don't want to inject each View class in my menu or main class.

Upvotes: 1

Views: 1525

Answers (2)

Calabacin
Calabacin

Reputation: 735

You need to annotate the class with @Named so that it is instantiated by the IoC, otherwise it will never get to see the @Inject.

Upvotes: 0

Sam Holder
Sam Holder

Reputation: 32936

Injections will only work in objects which the container is controlling the lifetime of. If you are just creating new objects how is the container going to know that the object has been created.

Usually the solution to your problem is one of the following:

  • not to create the object yourself, but to ask the container for the object. Although using the container outside of the composition root is a smell you should avoid.
  • create the object yourself and inject the dependencies manually. this requires the object creating the new object to have access to all the dependencies the objects it is going to create available at the point of creation. This may not be desirable so you may instead
  • delegate the creation to a factory class. This class takes all of the dependencies necessary to create the objects, and the class you are currently 'newing' the object in just has a single dependency on the factory.

Upvotes: 2

Related Questions