CDI - 在运行时动态注入对象(CDI - Injecting objects dynamica

2019-09-21 00:07发布

如何在运行时注入的对象? 例如,如果我要注入DerviedOne,DerivedTwo对象在运行时将在下面的例子中的测试类,我该怎么做呢? 我发现几个例子在春天,但我不使用Spring。 这是使用Java EE 6的动态Web项目与CDI。

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();
    }
}

Answer 1:

如果您想根据运行条件来选择一个实现你可以使用一个生产者方法与预选赛 。

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



文章来源: CDI - Injecting objects dynamically at runtime