Spring Boot @ConfigurationProperties示例

Spring Boot @ConfigurationProperties

Spring Boot @ConfigurationProperties使开发人员可以轻松地将整个.propertiesyml文件映射到一个对象中。

PS已通过Spring Boot 2.1.2测试。

1. @Value

1.1通常,我们使用@Value注入.properties值,这对于小型而简单的.properties文件来说是好的。 例如,

global.properties
email=test@mkyong.com
thread-pool=12
GlobalProperties.java
@Component
@PropertySource("classpath:global.properties")
public class GlobalProperties {

    @Value("${thread-pool}")
    private int threadPool;

    @Value("${email}")
    private String email;
    
    //getters and setters

}

1.2 @ConfigurationProperties的等效项

GlobalProperties.java
import org.springframework.boot.context.properties.ConfigurationProperties;

@Component
@PropertySource("classpath:global.properties")
@ConfigurationProperties
public class GlobalProperties {

    private int threadPool;
    private String email;

    //getters and setters

}

2. @ConfigurationProperties

2.1查看下面的复杂结构.propertiesyml文件,我们将如何通过@Value映射值?

application.properties
#Logging
logging.level.org.springframework.web=ERROR
logging.level.com.mkyong=DEBUG

#Global
email=test@mkyong.com
thread-pool=10

#App
app.menus[0].title=Home
app.menus[0].name=Home
app.menus[0].path=/
app.menus[1].title=Login
app.menus[1].name=Login
app.menus[1].path=/login

app.compiler.timeout=5
app.compiler.output-folder=/temp/

app.error=/error/

或等效的YAML。

application.yml
logging:
  level:
    org.springframework.web: ERROR
    com.mkyong: DEBUG
email: test@mkyong.com
thread-pool: 10
app:
  menus:
    - title: Home
      name: Home
      path: /
    - title: Login
      name: Login
      path: /login
  compiler:
    timeout: 5
    output-folder: /temp/
  error: /error/

注意
@ConfigurationProperties支持.properties.yml文件。

2.2 @ConfigurationProperties可以解决:

AppProperties.java
package com.mkyong;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@ConfigurationProperties("app") // prefix app, find app.* values
public class AppProperties {

    private String error;
    private List<Menu> menus = new ArrayList<>();
    private Compiler compiler = new Compiler();

    public static class Menu {
        private String name;
        private String path;
        private String title;

        //getters and setters

        @Override
        public String toString() {
            return "Menu{" +
                    "name='" + name + '\'' +
                    ", path='" + path + '\'' +
                    ", title='" + title + '\'' +
                    '}';
        }
    }

    public static class Compiler {
        private String timeout;
        private String outputFolder;

        //getters and setters

        @Override
        public String toString() {
            return "Compiler{" +
                    "timeout='" + timeout + '\'' +
                    ", outputFolder='" + outputFolder + '\'' +
                    '}';
        }

    }

    //getters and setters
}
GlobalProperties.java
package com.mkyong;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties // no prefix, find root level values.
public class GlobalProperties {

    private int threadPool;
    private String email;

	//getters and setters
}

3. @ConfigurationProperties验证

@ConfigurationProperties支持JSR-303 Bean验证。

3.1添加@Validated@ConfigurationProperties类,并javax.validation上的字段说明我们想要验证。

GlobalProperties.java
package com.mkyong;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;

@Component
@ConfigurationProperties
@Validated
public class GlobalProperties {

    @Max(5)
    @Min(0)
    private int threadPool;

    @NotEmpty
    private String email;

    //getters and setters
}

3.2设置线程池= 10

application.properties
#Global
email=test@mkyong.com
thread-pool=10

3.3启动Spring Boot,我们将遇到以下错误消息:

Console
***************************
APPLICATION FAILED TO START
***************************

Description:

Binding to target org.springframework.boot.context.properties.bind.BindException: 
	Failed to bind properties under '' to com.mkyong.GlobalProperties failed:

    Property: .threadPool
    Value: 10
    Origin: class path resource [application.properties]:7:13
    Reason: must be less than or equal to 5


Action:

Update your application's configuration

4.演示

$ git clone https://github.com/mkyong/spring-boot.git
$ cd externalize-config-properties-yaml
$ mvn spring-boot:run

access localhost:8080
演示

注意
有关更多详细信息,请参阅此官方Spring Boot外部化配置

下载源代码

$ git clone https://github.com/mkyong/spring-boot.git
$ cd externalize-config-properties-yaml
$ mvn spring-boot:运行

访问本地主机:8080

参考文献

翻译自: https://mkyong.com/spring-boot/spring-boot-configurationproperties-example/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值