3 Replies Latest reply on Apr 6, 2011 3:45 AM by samy

    Dependency Injection with Seam

    compiledmonkey

      I'm currently evaluating Seam and I have a question regarding dependency injection that I've yet to find an answer to.  I've been using Google Guice for dependency injection in my current JSF application.  It works great as I essentially have two implementations for a common set of interfaces.  I inject the required concrete classes based on which environment I'm deploying to.  Maybe not the common use for DI, but it works very well for me.  If I could change one thing it would be to have XML configuration over which classes are wired up.  That way I wouldn't need to recompile for each deployment, but I digress.


      Is this scenario something I could accomplish with Seam as well, without using Guice?  I've seen a lot about the annotations used for DI by Seam, but I've yet to see how the concrete classes are explicitly set for the framework to use.  Any direction on this subject would be helpful.  Thanks.

        • 1. Re: Dependency Injection with Seam
          kenclark

          It seems like there are a million ways to do what you want.  Here is one that uses Seam Bijection.  I have not actually done exactly this before but I think it should work.


          1) Create an action class that outjects the Interface you are interested in and has a corresponding factory method:



          public class MyAction 
          {
              @Out
              private MyInterface myInterface;
              
              @Factory("myInterface")
              public String loadAllTemplates()
              {
                  // Implement your loader however you like
                  if (x) myInterface = new X();
                  else myInterface = new Y();
              } 
          }



          2) Now inject that in any class that needs it.  You can scope it appropriately based on your needs.  Here is the simple injection code:



          public class TargetAction
          {
              @In
              private MyInterface myInterface;
          
              // ...
          
              public String myAction ()
              {
                  // Use myInterface
                  myInterface.doStuff();
              }
          }
          



          Good luck.


          ken



          • 2. Re: Dependency Injection with Seam
            pmuir

            Web Beans handles this really nicely through deployment types (but that is for the future).


            In the meantime, you can either use precedence if you have a distinct precedence (e.g. in a test env, always deploy test precedence over standard precedence) or only include the implementation you want in the archive/classpath.

            • 3. Re: Dependency Injection with Seam
              samy

              Ken Clark,


              you can give a simple example concerning MyInterface