学堂 学堂 学堂公众号手机端

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

lewis 2年前 (2023-10-05) 阅读数 7 #技术

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

  1. 创建一个配置属性类,用@ConfigurationProperties注解标记,同时指定一个前缀来区分不同配置属性:
importorg.springframework.boot.context.properties.ConfigurationProperties; importorg.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix="custom") publicclassCustomProperties{ privateStringproperty1; privateintproperty2; //省略getter和setter方法 }
  • application.propertiesapplication.yml中定义自定义配置属性:
  • custom.property1=value1 custom.property2=123
  • 在需要使用配置属性的地方注入CustomProperties类,SpringBoot会自动读取application.properties中定义的配置属性并注入到CustomProperties实例中:
  • importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.web.bind.annotation.GetMapping; importorg.springframework.web.bind.annotation.RestController; @RestController publicclassCustomController{ @Autowired privateCustomPropertiescustomProperties; @GetMapping("/properties") publicStringgetProperties(){ return"Property1:"+customProperties.getProperty1()+",Property2:"+customProperties.getProperty2(); } }

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


    版权声明

    本文仅代表作者观点,不代表博信信息网立场。

    热门