简体   繁体   中英

maven plugin parameter only available in execute

I'm writing a maven plugin with parameters.

The parameters are correctly initiated

[DEBUG] Configuring mojo '...' with basic configurator -->
[DEBUG]   (f) includes = [subpackage]
[DEBUG]   (f) outputDirectory = /Users/username/dev/project/output
[DEBUG]   (f) sources = [/Users/username/dev/project/src/main/java/io/packagea, /Users/username/dev/project/src/main/java/io/packageb]

The parameters are correctly initiated in method execute , but are then null in called methods : raises NullPointerException. If I pass the parameter of the mojo as parameters to called methodes, then

Here an example parameter :

@Parameter
private String[] includes;

I do not identify why.

The full code is on my github repo (on feature branch) : [ branch deleted as answer is clear on the origin of the issue ]

plugin can be called with mvn livingdoc:wordcloud on a project.

The plugin browse code for @Wordcloud annotations but no need to reproduce issue.

A Maven plugin is represented by a class that implements the Mojo interface (typically extends AbstractMojo ). It's annotated and such, so that Maven can recognize it, instantiate it (create a new instance) and execute it (call the execute method). In your case, this looks something like this:

@Mojo(name = "wordcloud")
public class WordCloudMojo extends AbstractMojo {

    @Parameter
    private String[] includes;

...

Maven makes sure that dependencies are satisfied, by injecting these into the new instance of your class, for example the includes field above.

If you create any other new and different instances of your plugin class, Maven doesn't concern itself with that, and dependencies will not be satisfied. In your case, like so:

public void execute() {
    final WordCloudMojo wordCloudMojo = new WordCloudMojo();
    Arrays.stream(includes).forEach(inc -> getLog().debug(inc));
    wordCloudMojo.scan(sources);

The stream(includes) will still use the Maven-injected dependency. But since you call scan on a new instance of WordCloudMojo , dependencies will not be satisfied (the field will likely be null ).

This would solve that:

final WordCloudMojo wordCloudMojo = new WordCloudMojo();
wordCloudMojo.includes = this.includes;

Excuse me for not using a mutator method. The this is redundant here, but emphasis the problem a bit.

Another solution would be: don't create a new instance of WordCloudMojo ? What's wrong with the one that Maven already made for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM