有什么方法可以在执行方法中访问插件属性吗?
我有一个具有一些属性的基本魔力,如下所示:
@Parameter(defaultValue = "DEV", property = "dbEnvironment", required = true)
protected Environment dbEnvironment;
@Parameter(defaultValue = "true", property = "validate")
protected boolean validate;
子 mojo 然后添加一些附加属性。我希望能够读取所有这些属性并验证它们,但如何做到这一点并不明显。当我通过调试运行它时,我看到了这个:
[DEBUG] Configuring mojo 'com.company.tools:something-maven-plugin:0.2.11-SNAPSHOT:export-job' with basic configurator -->
[DEBUG] (f) dbEnvironment = DEV
[DEBUG] (f) jobName = scrape_extract
[DEBUG] (f) project = MavenProject: com.company.tools:something-maven-plugin-it:1.0-SNAPSHOT @ /Users/selliott/intellij-workspace/tools-something-maven-plugin/something-maven-plugin/src/it/simple-it/pom.xml
[DEBUG] (f) session = org.apache.maven.execution.MavenSession@3fd2322d
[DEBUG] (f) validate = true
[DEBUG] -- end configuration --
所以,这些 Prop 看起来好像在某个地方,但是在哪里呢?我尝试从 session 、session.settings、session.request 中获取它们,但无济于事。
最佳答案
好吧,经过多次调试,我能够根据 AbstractConfigurationConverter 的工作原理(特别是 fromExpression 方法)弄清楚它。
要获取属性,您需要将以下内容添加到您的魔力中:
@Parameter(defaultValue = "${session}")
protected MavenSession session;
@Parameter(defaultValue = "${mojoExecution}")
protected MojoExecution mojoExecution;
从那里,您现在可以创建一个评估器和配置(也许您可以直接注入(inject)它们,我不确定),然后您可以执行以下操作:
PluginParameterExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator(session, mojoExecution);
PlexusConfiguration pomConfiguration = new XmlPlexusConfiguration(mojoExecution.getConfiguration());
for (PlexusConfiguration plexusConfiguration : pomConfiguration.getChildren()) {
String value = plexusConfiguration.getValue();
String defaultValue = plexusConfiguration.getAttribute("default-value");
try {
String evaluated = defaultIfNull(expressionEvaluator.evaluate(defaultIfBlank(value, defaultValue)), "").toString();
System.out.println(plexusConfiguration.getName() + " -> " + defaultIfBlank(evaluated, defaultValue));
} catch (ExpressionEvaluationException e) {
e.printStackTrace();
}
}
关于java - 在maven插件中获取mojo参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50823602/