How can I provide custom logic in a Maven archetype?

后端 未结 1 1452
猫巷女王i
猫巷女王i 2021-02-04 09:21

I\'m interested in creating a Maven archetype, and I think I have most of the basics down. However, one thing I\'m stuck on is that sometimes I want to use custom logic to fill

1条回答
  •  日久生厌
    2021-02-04 10:12

    The required properties section of the archetype-metatadata xml is used to pass additional properties to the velocity context, it is not meant for passing velocity engine configuration. So setting a property called userDirective will only make the variable $userDirective availble and not add a custom directive to the velocity engine.

    If you see the source code, the velocity engine used by maven-archetype plugin does not depend on any external property source for its configuration. The code that generates the project relies on an autowired (by the plexus container) implementation of VelocityComponent.

    This is the code where the velocity engine is initialized:

    public void initialize()
        throws InitializationException
    {
        engine = new VelocityEngine();
    
        // avoid "unable to find resource 'VM_global_library.vm' in any resource loader."
        engine.setProperty( "velocimacro.library", "" );
    
        engine.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, this );
    
        if ( properties != null )
        {
            for ( Enumeration e = properties.propertyNames(); e.hasMoreElements(); )
            {
                String key = e.nextElement().toString();
    
                String value = properties.getProperty( key );
    
                engine.setProperty( key, value );
    
                getLogger().debug( "Setting property: " + key + " => '" + value + "'." );
            }
        }
    
        try
        {
            engine.init();
        }
        catch ( Exception e )
        {
            throw new InitializationException( "Cannot start the velocity engine: ", e );
        }
    }
    

    There is a hacky way of adding your custom directive. The properties you see above are read from the components.xml file in the plexus-velocity-1.1.8.jar. So open this file and add your configuration property

    
      
        
          org.codehaus.plexus.velocity.VelocityComponent
          default
          org.codehaus.plexus.velocity.DefaultVelocityComponent
          
            
              
                resource.loader
                classpath,site
              
              ...
              
                userdirective
                com.jlarge.HyphenatedToCamelCaseDirective
              
            
          
        
      
    
    

    Next add your custom directive class file to this jar and run archetype:generate.

    As you see this is very fraglie and you will need to figure a way to distribute this hacked plexus-velocity jar. Depending on what you are planning to use this archetype for it might be worth the effort.

    0 讨论(0)
提交回复
热议问题