2016-02-03 152 views
0

我很难理解maven构建配置文件。maven - spring项目构建配置文件

基本上我的配置文件目录的结构是这样的

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") 

当我运行我的应用程序时,我把虚拟变量参数-Dspring.profiles.active=test所以它会加载在配置文件/测试下的e database.properties。然后,突然间我意识到,如果没有我在pom.xml中添加的配置,我可以做到这一点。即使我不需要我的pom.xml中的配置,这仍然是正确的构建配置文件的实施?

更新:这是我的分辨率 现在我明白了使用Maven型材的,我所做的是创建将举行基于主动轮廓结构中另一层。本是正确的,我正在混合春天配置文件与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") 

回答

2

这取决于你的目标是什么,看来你正在将Maven Profiles与Spring Profiles不同的概念混为一谈。使用Maven Profile可以在BUILD时间导致不同的行为,而Spring Profile会在RUN时间导致不同的行为。如果您只是想根据运行哪个配置文件加载不同的配置文件,则可能存在一些不同的可能性。如果您使用的是弹簧启动,您只需要在src/main/resources中有一个application-<profile-name>.properties文件 - 每个配置文件一个。如果您只使用Spring MVC,则可以有两个@Configuration classes,每个@Profile一个,每个配置@PropertiesSource以及适用于活动配置文件的database.properties文件。或者,您可以保持原样并通过SpEL中指定的目录路径加载文件。在任何情况下,您都不需要对Maven配置文件做任何事情,因为这些都只是运行时问题,并且src/main/resources下的所有内容都将默认包含在生成的包(war,ear,可执行jar等)中。

+0

在任何情况下,您都不需要对Maven配置文件做任何事情?我以为maven是为build时间? – fuzzy28

+0

你能建议我如何实现我的目标,当我想为两个不同的数据库连接有两个单独的db.properties文件时。 – fuzzy28

+0

个人而言,假设使用Spring Boot(我强烈推荐),我只需要在我的application.properties文件中包含连接字符串信息,并且对于src/main中的所有配置文件,我都拥有相同的配置/ resources/application.properties'然后我会在'/ src/main/resources/application-dev.properties'和'src/main/resources/application-test.properties'中设置特定于配置文件的数据库连接属性 – Ben