CDI - 在运行时动态注入对象

时间:2012-08-07 23:45:28

标签: class dynamic cdi inject

如何在运行时注入对象?例如,如果我想在运行时将DerivedTwo对象注入到以下示例中的Test类中,我该怎么做?我在Spring中找到了一些例子,但我没有使用Spring。这是一个使用Java EE 6的CDI动态Web项目。

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 个答案:

答案 0 :(得分:3)

如果您想根据运行时条件选择一个实现您可以producer method使用qualifiers

为了测试CDI应用,我强烈推荐Arquillian。 http://arquillian.org/