1 Reply Latest reply: Aug 23, 2012 11:15 AM by Bernhard Anzeletti RSS

to be or not to be (overloading the constructor)

pascal salg Newbie

Suppose I have 2 classes like:

 

public class classA{

     String test = "test";

     classA(String t){

          this.test = t;

     }

}

 

public class classB{

    

     @Inject classA class_a;

 

     classB(){

     }

 

     public void doStuff(){

          //do Stuff with class_a

     }

}

 

this throws an exception:

org.jboss.weld.exceptions.DeploymentException: WELD-001408 Unsatisfied dependencies for type ....

 

Am I right asuming, that for the injection in classB to work there must be a default constructor explicitly declared in classA (since I explicitly defined a non-default one, basic java stuff..) ? Does this mean, i would have to move stuff like initialization into a separate public method?

I'm currently involved in migrating an application from Seam 2 to Seam 3 and there are a lot of classes that get instanciated with a parametrized constructor..

(This may be a very simple case but I don't quite get it, as I am learning Seam 3 from scratch..)

  • 1. Re: to be or not to be (overloading the constructor)
    Bernhard Anzeletti Newbie

    Since Seam3 is an extension to CDI I took a glimpse into the CDI spec. According to JSR-299 (CDI), 3.1.1 Which Java classes are managed beans?, the following conditions must apply:

    ...

    * it has an appropriate constructor, either:

    ** the class has a constructor with no parameters, or

    ** the class declares a constructor annotated @Inject (Remark: as far as I know, a constructor that relies on injectable parameters)

    ...

    From the example code above I believe that ýour classA does not meet the "constructor condition" and, as a consequence, is not tread as a managed bean, which makes it hard for WELD to resolve the @Inject classA statement in classB, resulting in the error message. So maybe a constructor with no parameters is the appropriate solution. I would also recommend to use the standard class naming convention which requires uppercase letters for the first letter of a class name: ClassA instead of classA.

     

    As far as the "parametrized" constructors are concerned, they seem to need the @Inject annotation. In your case, the solution would probably be something like "class X { @Produces String testString = "test"; }  class A {private String test; @Inject A(String s) { this.test = s; } }"...