Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject @Parameter in different class in maven plugin

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

like image 755
Hilikus Avatar asked Oct 23 '25 16:10

Hilikus


2 Answers

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 );
}
like image 185
Robert Scholte Avatar answered Oct 25 '25 06:10

Robert Scholte


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 person element must map to a person field 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.query then the mapping mechanism will look in that package for an object named Person. 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.

like image 32
Marcono1234 Avatar answered Oct 25 '25 08:10

Marcono1234