3 Replies Latest reply on Oct 8, 2010 4:35 AM by 57skies

    Inject non default constructor

    57skies
      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
          wangliyu

          Not true,


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


          some other class:


          @InjectionTestInitParam
          public String getName()


          and then you should be doing following in other classes:


          @Inject
          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
            wangliyu

            should be




            @Produces
            @InjectTestInitParam
            public String getName()



            • 3. Re: Inject non default constructor
              57skies
              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");

              @Inject
              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