How to register decorated objects in Injection Dependency (PicoContainer) infrastructures?

I want to wrap several classes that implement the Job interface with the JobEnabledDecorator object, which determines whether it runs.

It's hard for me to figure out how to set this up in PicoContainer so that it knows that you need to create Job implementation objects using JobEnabledDecorator, wrapping them.

Is this possible in dependency frameworks?

Is this possible in PicoContainer?

If so, any help would be appreciated.

+3
source share
1 answer

, "". , factory, , . .

, - .

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
                )
            )
        );
    }
}

factory 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).

+7

Source: https://habr.com/ru/post/1726068/


All Articles