1

When using Plexus for MOJO plugin DI, is there a way to inject MOJO configuration parameter (annotated with @Parameter in the Mojo class) in other components as well?

In other words: Is there a way I can share Mojo parameters with other Plexus components apart from injecting the Mojo itself in other components, or resorting to hand-rolled "init method"? I was kinda hoping parameters would be managed by DI context.

Let's say I have a Mojo like this:

@Mojo
public class MyMojo extends AbstractMojo {

    @Parameter
    private String param;

    @Inject
    private SomeComponent component;
}

Then it would be nice to do something like this:

@Named
public class SomeComponent {
    @Inject // or whatever else
    private String param;

    // some methods that use param here
}

Instead of having to do:

@Mojo
public class MyMojo extends AbstractMojo {

    @Parameter
    private String param;

    @Inject
    private SomeComponent component;

    @Override
    public void execute() throws MojoExecutionException {
        component.setParam(param);
        ...
    }
}
mkvcvc
  • 1,515
  • 1
  • 18
  • 41
  • Keep in mind that `SomeComponent` can be used outside of the Maven plugin, since it's a (reusable) component. If it's that strongly related to your Mojo, maybe there's something wrong in the design and you shouldn't have it in the first place. Also, components are generally immutable and thread-safe; having a setter is not recommended. – Tunaki Nov 21 '16 at 09:43
  • What makes it strongly related to the mojo? The fact that it expects a string to be injected? It doesn't make it anymore coupled then a setter. Injecting it would be just a way to avoid boilerplate. – mkvcvc Nov 21 '16 at 09:45
  • The fact that it expects a String to be injected, in the context of using it from a plugin. What would happen if the Mojo is used twice in the same build, with different values of `param`? `SomeComponent` is shared and it's the same instance that'll be injected (by default, but you can't really change it from the plugin side). – Tunaki Nov 21 '16 at 09:48
  • Ok, so the question remains: how do you externalize component's configuration? – mkvcvc Nov 21 '16 at 10:21
  • That's the thing, `param` is not a configuration element of the component, since it changes while the component won't change. It shouldn't hold any state. You would pass that value as parameter, `myComponent.doTheFoo(param);` where that method does something, but doesn't mutate the component. Put another way, the plugin knows the component, but not the other way around. – Tunaki Nov 21 '16 at 10:26
  • How about project properties? These should have the same lifespan as the component, right? Would I be able to inject them? – mkvcvc Nov 21 '16 at 10:47
  • Not necessarily, you can have a multi-module project, (and furthermore, built in parallel). It really sounds like your component should not exist, or isn't decoupled enough from the Mojo. – Tunaki Nov 21 '16 at 10:50

0 Answers0