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

时间:2009-12-18 15:49:46

标签: java dependency-injection inversion-of-control decorator picocontainer

我想用JobEnabledDecorator对象包装许多实现Job接口的类,该对象确定它是否执行。

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

这在依赖注入框架中是否可行?

PicoContainer有可能吗?

如果是这样,我们将不胜感激。

1 个答案:

答案 0 :(得分:7)

您可能想要添加“行为”。简而言之,您需要注册一个行为工厂,它创建包装组件适配器的行为。通过一个例子来描述它更容易。

首先,你想要创建一个容器,就像这样。

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