Search code examples
spring-bootmavenmaven-3multi-module

Is it possible to load Spring-Boot properties from config folder within parent module of a Maven multi-module project?


Is it possible to load multiple Spring-Boot .yml config files from a config folder within parent module of a multi-module project?

So, structure looks like this:

parent-module/
  pom.xml
  config/
    application-prd.yml
    application-dev.yml
  module1
    pom.xml
    src/main/resources/
      logback-spring.xml
      bootstrap.yml

Is this possible? How can it be done?

So, if I execute from root folder of multi-module project, I would use this command:

mvn -pl module1 spring-boot:run
   OR
mvn spring-boot:run

And I would hope that the config folder would be included in the classpath? I am trying to do this but not getting it to work. Am I missing something?

We know this to be true: Child POMs inherit properties, dependencies, and plugin configurations from the parent. But shouldn't that mean that {parent}/config/application.yml is in the classpath already?

Example project to use for proving: https://github.com/djangofan/spring-boot-maven-multi-module-example . Clone it and modify if you think you can solve it.


Solution

  • No need to write code. You can use Exec Maven Plugin for this. Add the plugin to the parent module:

    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <version>1.6.0</version>
          <configuration>
            <mainClass>PACKAGE.MODULE_MAIN_CLASS</mainClass>
            <arguments>
              <argument>--spring.profiles.active=dev</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
    

    then run mvn install once and then mvn exec whenever you want to start the application.

    mvn exec:java -pl module1
    

    For more on Maven goals in a multi-module project, check this answer https://stackoverflow.com/a/11091569/512667 .

    Another way to configure this is like so, which requires the workingDirectory arg:

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <configuration>
            <mainClass>com.example.Application</mainClass>
            <workingDirectory>${maven.multiModuleProjectDirectory}</workingDirectory>
            <arguments>
                <argument>--spring.profiles.active=dev</argument>
            </arguments>
        </configuration>
    </plugin>
    

    In this case, execute:

    mvn spring-boot:run -pl module1