Ale*_*sky 3 java dependency-injection decorator inversion-of-control picocontainer
我想用JobEnabledDecorator对象包装许多实现Job接口的类,该对象确定它是否执行.
我无法弄清楚如何在PicoContainer中配置它,以便它知道用JobEnabledDecorator包装它们来创建Job实现对象.
这在依赖注入框架中是否可行?
PicoContainer有可能吗?
如果是这样,任何帮助将不胜感激.
你可能想要添加一个"行为".简而言之,您需要注册一个行为工厂,它创建包装组件适配器的行为.通过一个例子来描述它更容易.
首先,你想要创建一个容器,就像这样.
final MutablePicoContainer container = new PicoBuilder()
.withBehaviors(new JobEnabledDecorating())
.build();
Run Code Online (Sandbox Code Playgroud)
这意味着,一旦创建了基本对象 - 在您的情况下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
)
)
);
}
}
Run Code Online (Sandbox Code Playgroud)
工厂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-";
}
}
Run Code Online (Sandbox Code Playgroud)
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");
}
}
Run Code Online (Sandbox Code Playgroud)
回到我们的容器用法,请考虑这个例子.
final MutablePicoContainer container = new PicoBuilder()
.withBehaviors(new JobEnabledDecorating())
.build();
container.addComponent(Job.class, MyJob.class);
final Job job = container.getComponent(Job.class);
job.execute();
Run Code Online (Sandbox Code Playgroud)
运行此将打印:
before
execute
after
Run Code Online (Sandbox Code Playgroud)
当然,这是因为容器递给你一个JobEnabledDecorator(MyJob)物体.
| 归档时间: |
|
| 查看次数: |
557 次 |
| 最近记录: |