Ответ 1
Найден answer!
ОК, Паскаль прав, вот он для основания!!
Итак, вот самый чистый способ (насколько я знаю) добавить компиляцию classpath к выполнению вашего плагина.
Вот некоторые примеры кода из моего плагина code-gen, который фактически генерирует некоторый код шаблона на основе скомпилированного кода. Поэтому мне сначала нужно было скомпилировать код, затем проанализировать, сгенерировать некоторый код и затем скомпилировать снова.
-
Используйте
@configurator
в классе Mojo:/** * @goal generate * @phase process-classes * @configurator include-project-dependencies * @requiresDependencyResolution compile+runtime */ public class CodeGenMojo extends AbstractMojo { public void execute() throws MojoExecutionException { // do work.... } }
Обратите внимание на строку
@configurator
в заголовке javadoc, это важно для контейнера Ilex сплетения и это не просто другая строка комментария. -
Реализация конфигуратора
include-project-dependencies
. Это очень хороший класс, который я взял у Брайана Джексона, добавив его в источник вашего плагина./** * A custom ComponentConfigurator which adds the project runtime classpath elements * to the * * @author Brian Jackson * @since Aug 1, 2008 3:04:17 PM * * @plexus.component role="org.codehaus.plexus.component.configurator.ComponentConfigurator" * role-hint="include-project-dependencies" * @plexus.requirement role="org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup" * role-hint="default" */ public class IncludeProjectDependenciesComponentConfigurator extends AbstractComponentConfigurator { private static final Logger LOGGER = Logger.getLogger(IncludeProjectDependenciesComponentConfigurator.class); public void configureComponent( Object component, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm, ConfigurationListener listener ) throws ComponentConfigurationException { addProjectDependenciesToClassRealm(expressionEvaluator, containerRealm); converterLookup.registerConverter( new ClassRealmConverter( containerRealm ) ); ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); converter.processConfiguration( converterLookup, component, containerRealm.getClassLoader(), configuration, expressionEvaluator, listener ); } private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException { List<String> runtimeClasspathElements; try { //noinspection unchecked runtimeClasspathElements = (List<String>) expressionEvaluator.evaluate("${project.runtimeClasspathElements}"); } catch (ExpressionEvaluationException e) { throw new ComponentConfigurationException("There was a problem evaluating: ${project.runtimeClasspathElements}", e); } // Add the project dependencies to the ClassRealm final URL[] urls = buildURLs(runtimeClasspathElements); for (URL url : urls) { containerRealm.addConstituent(url); } } private URL[] buildURLs(List<String> runtimeClasspathElements) throws ComponentConfigurationException { // Add the projects classes and dependencies List<URL> urls = new ArrayList<URL>(runtimeClasspathElements.size()); for (String element : runtimeClasspathElements) { try { final URL url = new File(element).toURI().toURL(); urls.add(url); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Added to project class loader: " + url); } } catch (MalformedURLException e) { throw new ComponentConfigurationException("Unable to access project dependency: " + element, e); } } // Add the plugin dependencies (so Trove stuff works if Trove isn't on return urls.toArray(new URL[urls.size()]); } }
-
Вот часть сборки моего плагина, которую вам нужно будет добавить.
<modelVersion>4.0.0</modelVersion> <groupId>com.delver</groupId> <artifactId>reference-gen-plugin</artifactId> <name>Reference Code Genration Maven Plugin</name> <packaging>maven-plugin</packaging> <version>1.2</version> <url>http://maven.apache.org</url> <properties> <maven.version>2.2.1</maven.version> </properties> <build> <plugins> <plugin> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-maven-plugin</artifactId> <executions> <execution> <goals> <goal>descriptor</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-artifact</artifactId> <version>${maven.version}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-plugin-api</artifactId> <version>${maven.version}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-project</artifactId> <version>${maven.version}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-model</artifactId> <version>${maven.version}</version> </dependency> <dependency> <groupId>org.apache.maven</groupId> <artifactId>maven-core</artifactId> <version>2.0.9</version> </dependency> </dependencies>
Вот pom.xml плагина для тех, кому это нужно. Должна ли компилироваться проблема. (что-то не так с заголовком, поэтому игнорируйте его)