使用配置文件打包 Maven

问题描述 投票:0回答:2

我正在运行 spring boot,我有一个带有 3 个配置文件的 spring boot。它们如下。

applicaton.properties
{Empty file}

application-local.properties
test.variable = '1'

application-server.properties
test.variable = '2'

现在,当我运行我的 springboot 时,我总是运行一个或其他配置文件,具体取决于它是我的服务器还是本地环境。我有一个

@value
来解析这些值。但是,当我运行
mvn package
时,它吓坏了,因为它没有选择要打包的配置文件,并且在编译和尝试编译
@value
行时它找不到
test.variable
,因为它在
applicaton.properties 上不存在
.我如何
mvn package
将其编译成罐子?

另外,我知道运行这个应用程序时,我需要做的就是添加

-Dspring.profiles.active={profile}
,但是说我在
local
配置文件下编译,我以后还能在
server
配置文件下正常运行jar吗?

谢谢!

更多更新...我正在尝试运行此命令:

mvn package -P local

Maven 抛出这个异常:

    {bunch of other stacktrace stuff}
Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'test.variable' in value "${test.variable}"

请注意,当我在 intellij 中运行此应用程序时,在我的运行配置中,当我选择运行“本地”作为我的配置文件时,它运行完美,所以这只是让 maven 正确使用本地配置文件的问题。

java spring-boot maven
2个回答
0
投票

解决这个问题的多种选择:

  • 为变量提供默认值
@Value("${test.variable:my-default-value}")
String variable;
  • 通过 maven 设置配置文件进行测试
<build>
  <plugins>
     ...
    <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-surefire-plugin</artifactId>
        <configuration>
          <argLine>-Dspring.profiles.active=local</argLine>
        </configuration>
    </plugin>

  • 通过 src/test/resources/application.properties 提供测试变量
# application.properties in test/resources folder
test.variable = test

...


0
投票

Spring 配置文件只是您的应用程序的一个参数,spring 框架使用它来设置不同的 bean/属性,从而定义不同的应用程序行为。 spring 配置文件也是运行时参数,仅在运行应用程序期间使用。 Maven 配置文件和 spring 配置文件之间没有关系。

所以当你写的时候

当我运行 mvn package 时,它吓坏了,因为它没有选择要打包的配置文件,并且在编译和尝试编译 @value 行时它找不到 test.variable,因为它不存在于 applicaton.properties 中。我如何 mvn package 将其编译成 jar?

没有多大意义-因为

  1. maven
    不知道弹簧配置文件。
  2. maven
    不使用(也不应该使用)
    spring profile
    来编译/打包您的应用程序,因为
    spring profile
    是它的运行时参数。

我如何 mvn package 将其编译成 jar?

要将 spring boot 应用程序打包到 jar 中,可以使用 spring-boot-maven-plugin。最简单的开始方法是使用 https://start.spring.io/,它会为您准备初始的 maven 项目场景。

© www.soinside.com 2019 - 2024. All rights reserved.