maven - spring项目构建配置文件

时间:2016-02-03 05:23:21

标签: java spring maven

我很难理解maven构建配置文件。

基本上我的个人资料目录结构是这个

 src/main/resources/profiles/dev/database.properties

 src/main/resources/profiles/test/database.properties

我在pom.xml中有这个配置

      <build>
        ...
            <filters>


<filter>src/main/resources/profiles/${build.profile.id}/database.properties</filter>
            </filters>
            <resources>
                <resource>
                <filtering>true</filtering>
                <directory>src/main/resources/</directory>
            </resource>
        </resources>
    </build>

    <profiles>
        <profile>
            <id>dev</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <build.profile.id>dev</build.profile.id>
            </properties>
        </profile>
        <profile>
            <id>test</id>
            <properties>
                <build.profile.id>test</build.profile.id>
            </properties>
        </profile>
    </profiles>

然后在我的基于java的数据源配置中:

@Configuration
@PropertySource("classpath:profiles/${spring.profiles.active}/database.properties")

当我运行我的应用程序时,我将VM参数-Dspring.profiles.active=test置于其中,以便在profiles / test下加载database.properties。然后突然我意识到我可以在没有我在pom.xml中添加的配置的情况下执行此操作。这仍然是构建配置文件的正确实现,即使我不需要在我的pom.xml中进行配置吗?

更新:这是我的决议 现在我了解maven配置文件的使用,我所做的是创建另一个层,它将根据活动配置文件保存配置。 Ben是对的,我将弹簧型材与maven型材混合在一起。

我已使用此内容在资源下创建了另一个文件database.properties:

db.driver=${db.driver}
db.url=${db.url}
db.username=${db.username}
db.password=${db.password}

现在我的数据源配置仅引用该新层而不知道哪个配置文件被激活,因为maven将在编译期间解决此问题。

@Configuration
@PropertySource("classpath:database.properties")

1 个答案:

答案 0 :(得分:2)

这取决于您的目标是什么,看起来您将Maven配置文件与不同概念的Spring配置文件混淆。 Maven Profiles用于在BUILD时间引起不同的行为,而Spring Profiles则用于在RUN时间引起不同的行为。如果您只是根据正在运行的配置文件加载不同的配置文件,则有几种不同的可能性。如果您使用的是弹簧启动,则只需在application-<profile-name>.properties中有一个src/main/resources文件 - 每个配置文件一个。{1}}。如果您只使用Spring MVC,则可以有两个@Configuration classes,每个@Profile一个,并在每个@PropertiesSource中为活动配置文件配置相应的database.properties文件。或者,您可以保留原样,并通过SpEL中指定的目录路径加载文件。在任何情况下,您都不需要对Maven配置文件执行任何操作,因为这些只是运行时关注点,并且src / main / resources下的所有内容都将默认包含在生成的包中(war,ear,executable jar等)。

相关问题