Spring Boot属性配置的多种方式

Spring Boot属性配置的多种方式

Spring Boot是一种流行的Java框架,它简化了基于Spring的应用程序的创建和部署过程。在开发过程中,我们经常需要根据不同的运行环境来配置应用程序的属性。本文将介绍几种Spring Boot中设置属性的方法,并结合实例进行说明。

使用application.properties文件

Spring Boot默认从application.properties文件中加载属性。以下是如何在application.properties文件中设置属性的示例:

app.title=My App with application.properties

然后在Spring Boot应用程序中,我们可以使用@Value注解来注入这些属性:

@Component
class MyBean {
    @Value("${app.title}")
    private String appTitle;

    @PostConstruct
    public void startApplication() {
        System.out.printf("-- running application: %s --%n", appTitle);
    }
}

通过系统属性设置

我们也可以通过系统属性来设置应用程序的属性。例如,使用Maven运行Spring Boot应用程序时,可以如下设置:

mvn -q spring-boot:run -DtheMainClass="com.logicbig.example.ExampleMain" -Dspring-boot.run.jvmArguments="-Dapp.title='My app via JVM option'"

执行Jar时设置

在执行打包后的Jar文件时,我们可以通过-D参数来设置属性:

java -jar -Dapp.title="My App with System properties and exec jar" target/boot-different-ways-to-pass-app-properties-1.0-SNAPSHOT.jar

程序化设置属性

在Spring Boot应用程序启动时,我们可以通过编程的方式设置属性:

@SpringBootApplication
public class ExampleMain2 {
    public static void main(String[] args) {
        System.setProperty("app.title", "My Spring Application with system properties --");
        SpringApplication.run(ExampleMain2.class, args);
    }
}

使用SpringApplication.setDefaultProperties

我们还可以通过SpringApplication.setDefaultProperties方法来设置默认属性:

@SpringBootApplication
public class ExampleMain3 {
    public static void main(String[] args) {
        SpringApplication sa = new SpringApplication(ExampleMain3.class);
        Properties properties = new Properties();
        properties.setProperty("app.title", "My App with SpringApplication's default properties");
        sa.setDefaultProperties(properties);
        sa.run(args);
    }
}

使用命令行参数

在Maven命令中,我们可以使用-Dspring-boot.run.arguments来传递属性:

mvn -q spring-boot:run -Dspring-boot.run.arguments="--app.title='My App with application arguments'"

使用操作系统环境变量

最后,我们还可以通过设置操作系统的环境变量来传递属性:

set app.title="My App with O.S env variable"
mvn -q spring-boot:run

执行打包后的Jar文件时,如果设置了相同的环境变量,应用程序将使用该环境变量的值:

java -jar  target/boot-different-ways-to-pass-app-properties-1.0-Snapshot.jar

示例项目

本示例项目使用了以下依赖和技术:

  • Spring Boot 2.2.5.RELEASE
  • spring-boot-starter: 核心启动器,包括自动配置支持、日志记录和YAML。
  • JDK 1.8
  • Maven 3.5.4

通过上述方法,我们可以灵活地根据不同的运行环境配置Spring Boot应用程序的属性,从而提高应用程序的可移植性和灵活性。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

t0_54coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值