Custom type converter for Mojo configuration?

戏子无情 提交于 2019-12-11 07:12:04

问题


I need to use custom type, e.g., LunarDate, in my Mojo object:

class MyMojo extends AbstractMojo {

    /** @parameter */
    LunarDate lunarDate;

}

And I want to configure the parameter in <configuration> section in pom.xml.

<configuration>
     <lunarDate>丁丑年二月初四</lunarDate>
</configuration>

(The type LunarDate is just an example to illustrate the question)

I've already had the type converters, but how to enable them?


回答1:


DefaultBeanConfigurator is responsible for using DefaultConverterLookup, and it instantiates it directly without using the Plexus Container.

You could I suppose copy and modify it in a build extension, but registering your copy via @Component(role=BeanConfigurator.class) will likely have no effect; I have tried replacing standard Maven components in the past from build extensions and been told on maven-dev that it is not possible.

You could look up the default BeanConfigurator and use reflection to get its ConverterLookup converterLookup field, then call registerConverter with your custom convertor, but this would be fragile.

Probably best is to just give up, declare your Mojo parameter to be of type String, and do the conversion explicitly in execute.




回答2:


For newer Maven (tested with Maven 3.3.1) you can now subclass BasicComponentConfigurator to access the DefaultConverterLookup as a member variable:

@Component(role = ComponentConfigurator.class, hint = "basic")
public class ExtendedComponentRegistrator 
        extends BasicComponentConfigurator  
        implements Initializable {

    @Override
    public void initialize() throws InitializationException {
        converterLookup.registerConverter(new MyCustomConverter());
    }
}

Then in the pom.xml enable the generation of plexus meta data:

<plugin>
  <groupId>org.codehaus.plexus</groupId>
  <artifactId>plexus-component-metadata</artifactId>
  <executions>
    <execution>
      <goals>
        <goal>generate-metadata</goal>
      </goals>
    </execution>
  </executions>
</plugin>


来源:https://stackoverflow.com/questions/10188534/custom-type-converter-for-mojo-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!