如何注册依赖注入框架(PicoContainer)中的装饰对象?
问题描述:
我想用一个JobEnabledDecorator对象来包装一些实现Job接口的类,以确定它是否执行。如何注册依赖注入框架(PicoContainer)中的装饰对象?
我很难搞清楚如何在PicoContainer中配置它,以便它知道使用包装它们的JobEnabledDecorator创建Job实现对象。
这是可能的依赖注入框架?
PicoContainer中可能吗?
如果是这样,任何帮助,将不胜感激。
答
您可能需要添加“行为”。简言之,您需要注册一个行为工厂,创建包装组件适配器的行为。通过一个例子来描述时更容易描述。
首先,你要创建一个容器,像这样。
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)
对象。
感谢您的好评。不幸的是,我只能给你一个upvote! – 2009-12-19 18:47:45
这对你很有帮助,那才是最重要的。 :-) – 2009-12-20 16:45:37