gpt4 book ai didi

java - 如何在依赖注入(inject)框架(PicoContainer)中注册装饰对象?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:36:19 27 4
gpt4 key购买 nike

我想用一个确定是否执行的 JobEnabledDecorator 对象包装一些实现 Job 接口(interface)的类。

我无法弄清楚如何在 PicoContainer 中配置它,以便它知道创建 Job 实现对象并用 JobEnabledDecorator 包装它们。

这在依赖注入(inject)框架中可能吗?

在 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) 对象。

关于java - 如何在依赖注入(inject)框架(PicoContainer)中注册装饰对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1928982/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com