我想用一个JobEnabledDecorator对象包装一些实现Job接口的类,该对象决定它是否执行。
我在弄清楚如何在PicoContainer中配置它时遇到了麻烦,这样它就知道如何使用包装它们的JobEnabledDecorator来创建作业实现对象。
这在依赖注入框架中是可能的吗?
在PicoContainer中是可能的吗?
如果是这样,任何帮助都将不胜感激。
发布于 2009-12-19 04:55:39
你可能想要添加一个“行为”。简而言之,您需要注册一个行为工厂,该工厂创建包装组件适配器的行为。在浏览示例时,它更容易描述。
首先,你想创建一个容器,就像这样。
final MutablePicoContainer container = new PicoBuilder()
.withBehaviors(new JobEnabledDecorating())
.build();这意味着,一旦创建了基本对象-在您的示例中是Job -您就需要向其添加一些额外的东西。有许多内置的行为,但您需要自己的行为:JobEnabledDecorating。
public class JobEnabledDecorating extends AbstractBehaviorFactory {
@Override
public ComponentAdapter createComponentAdapter(
final ComponentMonitor componentMonitor, final LifecycleStrategy lifecycleStrategy,
final Properties componentProperties, final Object componentKey,
final Class componentImplementation, final Parameter... parameters) throws PicoCompositionException
{
return componentMonitor.newBehavior(
new JobEnabledDecorated(
super.createComponentAdapter(
componentMonitor, lifecycleStrategy, componentProperties,
componentKey, componentImplementation, parameters
)
)
);
}
}工厂通过包装组件适配器来创建JobEnabledDecorated行为,组件适配器反过来提供您的实例。真正的工作现在已经在这个行为中完成了。
public class JobEnabledDecorated extends AbstractBehavior<Job> {
public JobEnabledDecorated(final ComponentAdapter<Job> delegate) {
super(delegate);
}
@Override
public Job getComponentInstance(final PicoContainer container, final Type into)
throws PicoCompositionException {
final Job instance = super.getComponentInstance(container, into);
return new JobEnabledDecorator(instance);
}
@Override
public String getDescriptor() {
return "JobEnabledDecorator-";
}
}getComponentInstance请求该作业,添加装饰器,并将此包装对象作为新实例返回。你必须在这里添加你自己的逻辑。
public interface Job {
void execute();
}
public class JobEnabledDecorator implements Job {
private Job delegate;
public JobEnabledDecorator(final Job delegate) {
this.delegate = delegate;
}
@Override
public void execute() {
System.out.println("before");
delegate.execute();
System.out.println("after");
}
}
public class MyJob implements Job {
@Override
public void execute() {
System.out.println("execute");
}
}回到我们的容器使用,考虑这个例子。
final MutablePicoContainer container = new PicoBuilder()
.withBehaviors(new JobEnabledDecorating())
.build();
container.addComponent(Job.class, MyJob.class);
final Job job = container.getComponent(Job.class);
job.execute();运行此命令将打印以下内容:
before
execute
after当然,这是因为容器传递给您一个JobEnabledDecorator(MyJob)对象。
https://stackoverflow.com/questions/1928982
复制相似问题