Search code examples
dependency-injectionjava-ee-6cdi

How to inject an instance of a class with a parameterized constructor using CDI (Java EE 6 only)


I'm new to CDI, tried searching for the usage, could not find anything and so posting the question. I'm trying to figure how I can inject an instance of a class with a parameterized constructor only using CDI. I'm not using Spring so, how it is done in spring does not help. Here is a sample I've created to show what's the issue. My @Inject will not work in this scenario.

    public class A 
    {
        public A(boolean deliverFromLocalWarehouse)
        {
            if(deliverFromLocalWarehouse)
            {
                wareHouseId = new Integer(10); 
            }
            else 
            {
                wareHouseId = new Integer(100);
            }
        }

        public void deliver()
        {
            //get wareHouse address by Id and initiate delivery.   
        }

        private Integer wareHouseId = null;
    }

    public class B 
    {

        @Inject
        private A a;
    }

Thanks Srikrishna Kalavacharla


Solution

  • If the constructor parameter should come from a bean, I think you can simply annotate it:

    public A(@Inject boolean localWarehouse) { ...
    

    and inject it with

    @Inject A a;
    

    If you want two different instances of A (with different constructor arguments), you could subclass them:

    public AForLocalWarehouse extends A {
        public AForLocalWarehouse() {
            super(true);
        }
    }
    

    and inject them with

    @Inject AForLocalWarehouse a;
    

    or use a producer method with qualifiers:

    @Produces @LocalWarehouse
    public A localWarehouse() { return new A(true); }
    
    @Produces @RemoteWarehouse
    public A remoteWarehouse() { return new A(false); }
    

    and inject them with

    @Inject @LocalWarehouse A a;
    @Inject @RemoteWarehouse A a;