Get directory path of maven plugin in its own Mojo

2019-07-23 02:01发布

问题:

I am creating a custom maven plugin. In one of its Mojos, I am reading a Xpp3Dom object from XML file using following code piece:

File pluginsFile = new File(
        "absolute-path-to-file/plugins.xml");
Xpp3Dom Xpp3DomObject = new Xpp3Dom("plugins");
try {
    FileReader reader = new FileReader(pluginsFile);
    Xpp3DomObject = Xpp3DomBuilder.build(reader);
    reader.close();
} catch (Exception e) {
    // TODO throw exception
}

The XML file from which I am reading (plugins.xml) is stored in src/main/resources of the maven plugin itself. My question is, how do I point to that XML file without explicitly stating the absolute path to that file?

To be clear: I want this file to be under the directory of my maven plugin. It cannot be outside the maven plugin as it is a necessary part of the maven plugin and should not be changed by other maven projects that consume this plugin.

I have searched for a variable/method in Maven Mojo that would give me the absolute location of the maven plugin itself. If I get that, then I can just give the location as value-of-that-variable/src/main/resources/plugins.xml. But I am unable to find such variable. I have also tried for a way to pass properties from Maven plugin POM to one of its Mojos so that I can pass project.build.directory, but cannot find a way.

To be clear: I want to access a file that is under the maven plugin directory, in one of its Mojos.

Any suggestions will help.

回答1:

I think the easiest form to read some of the own plugin's resources files is through the getResourceAsStream() API, because sooner or later, your plugin will be delivered as a JAR, and then the src directory will dissapear and there will remain only classpath resources:

try (InputStream input=getClass().getClassLoader().getResourceAsStream("plugins.xml")){
    try(Reader reader=new InputStreamReader(input));
    {
        Xpp3Dom Xpp3DomObject = Xpp3DomBuilder.build(input);
    } catch (Exception e) {
        ...
    }
}

Anyway, in this way there is a risk that some other JAR of the classpath should contain a plugins.xml file by chance. To avoid (or at least reduce) this risk, you should package it:

src\
    main\
        resources\
            foo\
                bar\
                    MyMojo.java
                    plugins.xml

... and in this case, you must read it through getClass().getResourceAsInputStream().