I am writing a maven plugin and based on my previous experience i know that my mojo class will end up with a bunch of @Parameters to configure it. What I would like to do is instead of having those configuration parameters injected in the mojo class, I would like to have them injected in a second, configuration-only class. Is this possible?
The current way I do it is the mojo class just constructs a Configuration object where it passes all the injected parameters. Something like this
@Mojo
public class MyMojo extends AbstractMojo {
private MyConfig myConfig;
@Parameter
private String myArg1;
...
public void execute() {
myConfig = new MyConfig(myArg1, myArg2, ...);
}
}
But this is rather ugly. I want the DI to happen directly in Config
If MyConfig is a pojo, you can use the @Parameter here as well, However, you config will look like:
<configuration>
<myConfig>
<someField>value</someField>
</myConfig>
</configuration>
The second trick is to use setters, because an @Parameter-annotated field will use the matching public setter, if there is one.
private MyConfig myConfig = new MyConfig();
@Parameter
private String someField;
// matching setter for @parameter-annotated field
public void setSomeField( String field )
{
myConfig.setSomeField( field );
}
You can use your MyConfig POJO as @Parameter:
@Mojo
public class MyMojo extends AbstractMojo {
@Parameter
private MyConfig myConfig;
...
}
The rules for mapping complex objects are as follows:
- There must be a private field that corresponds to name of the element being mapped. So in our case the
personelement must map to apersonfield in the mojo.- The object instantiated must be in the same package as the Mojo itself. So if your mojo is in
com.mycompany.mojo.querythen the mapping mechanism will look in that package for an object namedPerson. As you can see the mechanism will capitalize the first letter of the element name and use that to search for the object to instantiate.
Source
However, using the @Parameter for fields of MyConfig has no effect, see this thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With