cksrc
cksrc

Reputation: 2347

Java CDI inject non zero args constructor

I'm playing with java standard CDI and there is one concept I cannot get my head around. In the example below the Application class "requires" the Person class which cannot be injected since it has non-zero args constructor. How should I handle this scenario with CDI?

@Default
class Person {
 private String name;
 Person(String name) {
  this.name=name;
 }
 String getName() {
  return this.name;
 }
}


class Application {
  @Inject
  public Application(Instance<Person> p)
}

Upvotes: 2

Views: 995

Answers (1)

jvalli
jvalli

Reputation: 721

There are three ways to inject objects without a no-args constructor. One is to use a producer to create the object.

@Produces 
private Person producePerson() {
    return new Person(name);
}

The second is to annotate one of the constructors with @Inject and make sure all of the parameters are valid injection targets.

class Person {
    private String name;

    @Inject
    Person(String name) {
        this.name=name;
    }

    String getName() {
        return this.name;
    }
}

and somewhere else:

@Produces 
private String producePersonName() {
    return name;
}

(Setting up multiple of these kinds of injections may require creating some qualifier annotations)

The third is to mess around with CDI container initialization with a custom extension, but that is overkill for such a relatively simple need.

Upvotes: 3

Related Questions