3 Replies Latest reply on Oct 8, 2010 4:35 AM by eugene rabii

    Inject non default constructor

    eugene rabii Newbie
      Well, first hello to everyone. My question is very simple (sorry if it's a total newbie question...).

      Imagine I have a class :

      public class InjectionTest{
          private String name;
          InjectionTest(String name){
               this.name = name;

      Now I want to use/inject this class into a Servlet for example - it does not matter for what reason. From what I have seen so far - this is impossible, right? Even if I annotate the constructor with @Inject - I still get an error.
      So, basically, I need to provide a default constructor so that an Object gets injected? :| Please correct me if I am wrong.

      Thank you, Eugene.
        • 1. Re: Inject non default constructor
          Wang Liyu Apprentice

          Not true,

          public InjectionTest(@InjectionTestInitParam String name) {...}

          some other class:

          public String getName()

          and then you should be doing following in other classes:

          private InjectionTest test;

          typical usage you should be able to see some code in the Weld code, for example the ServletConversation.

          • 2. Re: Inject non default constructor
            Wang Liyu Apprentice

            should be

            public String getName()

            • 3. Re: Inject non default constructor
              eugene rabii Newbie
              Well I had the same idea, use a Producer. But things complicate for me when I have the following scenario. For example the name is unknown until Runtime, let's suppose that is it the username of the user. So, I need to Inject the InjectTest class, but the String 'name' is unknown until Runtime. Basically I have to do something like Inject into a Producer method or something like this. Producer methods do not except any parameters besides the InjectionPoint (of course I could use more producers inside producers) - that is not much of a help to me.

              Button-line: I want to inject an InjectTest, but with different name values. I want to be able to do something like this:

              // For example username taken from the HttpServlerRequest
              String name = request.getParameter("username");

              InjectTest injectTest(name)

              of course it's wrong here - it is impossible to do this, but the idea that I want to do is may be a bit more clear.
              Is this possible with Weld?

              Thank you for your time! Eugene