How can I write maven build to add resources to classpath?

后端 未结 3 1114
鱼传尺愫
鱼传尺愫 2020-12-04 21:56

I am building a jar using maven with simple maven install. If I add a file to src/main/resources it can be found on the classpath but it has a config folder whe

相关标签:
3条回答
  • 2020-12-04 22:22

    By default maven does not include any files from "src/main/java".

    You have two possible way to that.

    1. put all your resource files (different than java files) to "src/main/resources" - this is highly recommended

    2. Add to your pom (resource plugin):

     <resources>
           <resource>
               <directory>src/main/resources</directory>
            </resource>
                <resource>
                    <directory>src/main/java</directory>
                    <includes>
                        <include>**/*.xml</include>
                    </includes>
                </resource>
      </resources>
    
    0 讨论(0)
  • 2020-12-04 22:30

    A cleaner alternative of putting your config file into a subfolder of src/main/resources would be to enhance your classpath locations. This is extremely easy to do with Maven.

    For instance, place your property file in a new folder src/main/config, and add the following to your pom:

     <build>
        <resources>
            <resource>
                <directory>src/main/config</directory>
            </resource>
        </resources>
     </build>
    

    From now, every files files under src/main/config is considered as part of your classpath (note that you can exclude some of them from the final jar if needed: just add in the build section:

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>my-config.properties</exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    

    so that my-config.properties can be found in your classpath when you run your app from your IDE, but will remain external from your jar in your final distribution).

    0 讨论(0)
  • 2020-12-04 22:35

    If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

    1. *.jar is not correctly loaded (maybe typo in the path?)
    2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties
    0 讨论(0)
提交回复
热议问题