如何在运行时注入的对象? 例如,如果我要注入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();
}
}