【问题标题】:Accessing a project resource from a plugin in Maven从 Maven 中的插件访问项目资源
【发布时间】:2012-12-13 08:04:11
【问题描述】:

我编写了一个 Maven 插件,它在独立运行时运行良好。我在插件源代码中有一些自定义 XML 资源文件,这些文件在测试时对插件可见和可访问(下面的插件 POM)。所以我安装了插件,一切都很好。

现在我创建一个引用新安装插件的新项目(下面的项目 POM)。我有一些类似于插件项目中嵌入的自定义 XML 资源文件。

项目结构如下:

tester
|   pom.xml
|
+---src
|   +---main
|   |   +---java
|   |   |   \---[BLAH}
|   |   |
|   |   \---resources
|   |           tester-catalog-env.xml
|   |
|   \---test
|       \---java
|           \---[BLAH]

在插件中我有以下方法:

    public TesterProcessCatalog getTesterProcessCatalog(Properties properties) throws TesterDataSourceException {
        try {
            InputStream in = getClass().getClass().getResourceAsStream("tester-catalog-env.xml");
            Reader reader = ReaderFactory.newXmlReader(in);
            return readCatalog(reader);

        } catch (IOException e) {
            throw new TesterDataSourceException("Error reading catalog", e);
        }
    }

行:

InputStream in = getClass().getClass().getResourceAsStream("tester-catalog-env.xml");

在使用mvn tester:test(在插件mojo中定义)从项目运行时返回null,即使我可以看到资源存在于类路径中。我已经尝试了以下

InputStream in = getClass().getClass().getResourceAsStream("/tester-catalog-env.xml");

这也会返回null

如果我将资源文件复制到插件资源目录并运行,它可以正常工作。

最终我想要实现的是在项目资源目录中有多个配置文件(即 tester-catalog-xxx.xml - 其中 xxx 可以是用户创建的新文件),当像 @ 这样的命令时987654327@ 运行时会加载名为 tester-catalog-env2.xml 的文件。

关于我做错了什么有什么想法吗?

Maven 信息

Apache Maven 3.0.4 (r1232337; 2012-01-17 10:44:56+0200)
Maven 主页:C:\Apps\apache-maven-3.0.4
Java 版本:1.6.0_35,供应商:Sun Microsystems Inc.
Java 主页:C:\java\jdk1.6.0_35\jre
默认语言环境:en_GB,平台编码:Cp1252
操作系统名称:“windows xp”,版本:“5.1”,arch:“x86”,家族:“windows”

插件 POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.testing.tester.maven</groupId>
    <artifactId>tester</artifactId>
    <packaging>maven-plugin</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>tester Maven Mojo</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.2-beta-5</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-component-annotations</artifactId>
            <version>1.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>com.sun</groupId>
            <artifactId>tools</artifactId>
            <version>1.6</version>
            <scope>system</scope>
            <systemPath>C:\java\jdk1.6.0_35\lib\tools.jar</systemPath>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.brsanthu</groupId>
            <artifactId>data-exporter</artifactId>
            <version>1.0.0</version>
            <!-- http://code.google.com/p/data-exporter/wiki/UserGuide -->
            <!-- mvn install:install-file -DgroupId=com.brsanthu -DartifactId=data-exporter -Dversion=1.0.0 -Dpackaging=jar -Dfile=http://data-exporter.googlecode.com/files/data-exporter-1.0.0.jar-->
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.plexus</groupId>
                <artifactId>plexus-component-metadata</artifactId>
                <version>1.5.5</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate-metadata</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-source-plugin</artifactId>
                <executions>
                    <execution>
                        <id>attach-sources</id>
                        <goals>
                            <goal>jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

项目 POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.testing.tester</groupId>
  <artifactId>tester</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>tester</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
      <dependency>
          <groupId>com.testing.tester.maven</groupId>
          <artifactId>tester</artifactId>
          <version>1.0-SNAPSHOT</version>
      </dependency>
  </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>com.testing.tester.maven</groupId>
                <artifactId>tester</artifactId>
                <version>1.0-SNAPSHOT</version>
            </plugin>
        </plugins>
    </build>
</project>

【问题讨论】:

    标签: java maven maven-3


    【解决方案1】:

    我找到了一个可行的解决方案。这个post 详细说明了所需的步骤。

    基本上我在插件中添加了以下类(我已经删除了原始帖子中对 LOGGER 的引用)

        /**
         * A custom ComponentConfigurator which adds the project's 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 { 
    
            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);
                    } catch (MalformedURLException e) {
                        throw new ComponentConfigurationException("Unable to access project dependency: " + element, e);
                    }
                }
    
                // Add the plugin's dependencies (so Trove stuff works if Trove isn't on
                return urls.toArray(new URL[urls.size()]);
            }
    
        }
    

    然后添加

    @configurator include-project-dependencies
    

    对于我的 mojo 声明,它有效!

    【讨论】:

      【解决方案2】:

      我认为您需要将 testerProcessCatalog 文件指定为 Maven 插件属性:

      /**
       * @parameter expression="${tester.testerProcessCatalog}"
       * default-value="${basedir}/src/main/resources/tester-catalog-env.xml"
       */
      private File testerProcessCatalog; 
      

      注意:我在某处看到您现在可以使用 Java 注释而不是 Javadoc 注释,但我还没有尝试过。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        相关资源
        最近更新 更多