Custom type converter for Mojo configuration?

后端 未结 3 921
刺人心
刺人心 2021-01-23 16:04

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

class MyMojo extends AbstractMojo {

    /** @parameter */
    LunarDate lunarDate;

         


        
3条回答
  •  耶瑟儿~
    2021-01-23 16:34

    I was able to solve this by defining a ConfigurationConverter (my target type is a AnyLicenseInfo):

    @NoArgsConstructor @ToString
    public class LicenseConverter extends AbstractBasicConverter {
        private static final Class TYPE = AnyLicenseInfo.class;
    
        @Override
        public boolean canConvert(Class type) { return type.equals(TYPE); }
    
        @Override
        public Object fromString(String string) throws ComponentConfigurationException {
            Object object = null;
    
            try {
                object =
                    TYPE.cast(LicenseInfoFactory.parseSPDXLicenseString(string));
            } catch (Exception exception) {
                String message =
                    "Unable to convert '" + string + "' to " + TYPE.getName();
    
                throw new ComponentConfigurationException(message, exception);
            }
    
            return object;
        }
    }
    

    Registering it with a custom ComponentConfigurator:

    @Named("license-mojo-component-configurator")
    @NoArgsConstructor @ToString @Slf4j
    public class LicenseMojoComponentConfigurator extends BasicComponentConfigurator {
        @PostConstruct
        public void init() {
            converterLookup.registerConverter(new LicenseConverter());
        }
    
        @PreDestroy
        public void destroy() { }
    }
    

    And then specifying the configurator in the @Mogo annotation:

    @Mojo(name = "generate-license-resources",
          configurator = "license-mojo-component-configurator",
          requiresDependencyResolution = TEST,
          defaultPhase = GENERATE_RESOURCES, requiresProject = true)
    @NoArgsConstructor @ToString @Slf4j
    public class GenerateLicenseResourcesMojo extends AbstractLicenseMojo {
    

提交回复
热议问题