Spring Boot允许您从外部配置文件(如application.properties或application.yml)中读取配置参数。在将Spring Boot应用程序打包为JAR文件时,您可以将外部配置文件包含在JAR文件中,并在运行时从JAR文件中读取它们。

以下是将外部配置文件包含在Spring Boot JAR文件中并从中读取参数值的步骤:

  1. 将外部配置文件(例如application.properties或application.yml)放在src/main/resources目录下。
  2. 在pom.xml文件中添加以下插件配置,以在构建JAR文件时将外部配置文件包含在JAR文件中:
<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <configuration>
        <resources>
          <resource>
            <directory>src/main/resources</directory>
            <includes>
              <include>application.properties</include>
              <include>application.yml</include>
            </includes>
          </resource>
        </resources>
      </configuration>
    </plugin>
  </plugins>
</build>
  1. 在Spring Boot应用程序中,您可以使用@Value注释从外部配置文件中读取参数值。例如,如果您的配置文件包含以下属性:
myapp.username=johndoe
myapp.password=secret

您可以使用以下代码从应用程序中读取这些值:

@Value("${myapp.username}")
private String username;

@Value("${myapp.password}")
private String password;

请注意,您需要在应用程序类中使用@SpringBootApplication注释来启用Spring Boot自动配置

springboot 打包为jar后读取外部配置文件并获取参数值

原文地址: https://www.cveoy.top/t/topic/eakP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录