Linux 拨号vps windows公众号手机端

SpringBoot中怎么自定义配置属性

lewis 9年前 (2016-11-13) 阅读数 9 #程序编程
文章标签 springboot

在SpringBoot中,可以通过创建一个@ConfigurationProperties注解的类来自定义配置属性。以下是一个示例:

  1. 创建一个配置属性类,用@ConfigurationProperties注解标记,同时指定一个前缀来区分不同配置属性:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "custom")
public class CustomProperties {
    private String property1;
    private int property2;

    // 省略getter和setter方法
}
  1. application.propertiesapplication.yml中定义自定义配置属性:
custom.property1=value1
custom.property2=123
  1. 在需要使用配置属性的地方注入CustomProperties类,SpringBoot会自动读取application.properties中定义的配置属性并注入到CustomProperties实例中:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CustomController {

    @Autowired
    private CustomProperties customProperties;

    @GetMapping("/properties")
    public String getProperties() {
        return "Property1: " + customProperties.getProperty1() + ", Property2: " + customProperties.getProperty2();
    }
}

这样,就可以在SpringBoot中自定义配置属性并使用了。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门