CDI - Injecting objects dynamically at runtime

末鹿安然 提交于 2020-01-02 15:52:32

问题


How do I inject objects at runtime? For example, if I want to inject DerviedOne, DerivedTwo objects at runtime into the Test class in the following example, how do I do that? I found a few examples in Spring, but I'm not using Spring. This is a Dynamic Web Project with CDI using Java EE 6.

public abstract class Base 
{
    public Base(String initiator)
    {
        this.initiator = initiator;
    }

    public abstract void process();

    public void baseProcess()
    {
        System.out.println("base process");
        process();
    }

    public String getInitiator()
    {
        return initiator;
    }

    private String initiator;
}



public class BaseUtil 
{
    public long start()
    {
        return System.currentTimeMillis();
    }

    public long stop()
    {
        return System.currentTimeMillis();
    }
}


public class DerivedOne extends Base 
{
    public DerivedOne(String initiator) 
    {
        super(initiator);
    }

    @Override
    public void process() 
    {
        long start = baseUtil.start();
        System.out.println(getInitiator() + " process");
        long stop = baseUtil.stop();
        System.out.println(stop - start);
    }

    @javax.inject.Inject
    private BaseUtil baseUtil;
}

public class DerivedTwo extends Base 
{
    public DerivedTwo(String initiator) 
    {
        super(initiator);
    }

    @Override
    public void process() 
    {
        long start = baseUtil.start();
        System.out.println(getInitiator() + " process");
        long stop = baseUtil.stop();
        System.out.println(stop - start);
    }

    @javax.inject.Inject
    private BaseUtil baseUtil;

}

@Startup
@Singleton
public class Test 
{
    @PostConstruct
    public void init()
    {
        String initiator = "two";
        Base base = null;

        if("one".equals(initiator))
        {
            base = new DerivedOne("DerivedOne");
        }
        else if("two".equals(initiator))
        {
            base = new DerivedTwo("DerivedTwo");
        }

        base.baseProcess();
    }
}

回答1:


If you want to select one implementation based on runtime conditions You can use a producer method with qualifiers.

For testing CDI application I highly recommend Arquillian. http://arquillian.org/



来源:https://stackoverflow.com/questions/11855687/cdi-injecting-objects-dynamically-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!