2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > SpringBoot获取YAML配置文件中的自定义属性值

SpringBoot获取YAML配置文件中的自定义属性值

时间:2021-02-04 11:19:55

相关推荐

SpringBoot获取YAML配置文件中的自定义属性值

SpringBoot支持使用Properties和YAML两种配置方式。两者功能类似,都能完成SpringBoot的配置,但是Properties的优先级要高于YAML(YAML语言的文件以“.yml”为后缀)。

使用application.yml文件配置SpringBoot项目。主要对SpringBoot项目的端口号、超时时间、参数值等进行配置。YAML文件的好处是——它采用的是树形结构,一目了然。如下:

server:port: 8080servlet:session:timeout: 30Mtomcat:uri-encoding: UTF-8userinfo:user-id: 1user-name: pan_junbiao的博客blog-url: /pan_junbiaohobbys: -[篮球,足球,羽毛球,乒乓球,游泳]blog-remark: 您好,欢迎访问 pan_junbiao的博客

下面将介绍SpringBoot项目中获取YAML配置文件中的自定义属性值。

1、方法一:使用@Value注解

示例:创建 com.pjb.properties 包,创建 UserProperties类(用户配置信息类),并使用@Value注解注入配置文件内容,以装载配置文件的信息。

package com.pjb.properties;import org.springframework.beans.factory.annotation.Value;import org.ponent;/*** 用户配置信息类* @author pan_junbiao**/@Componentpublic class UserProperties{/*** 用户编号*/@Value("${userinfo.user-id}")private int userId;/*** 用户名称*/@Value("${userinfo.user-name}")private String userName;/*** 博客地址*/@Value("${userinfo.blog-url}")private String blogUrl;/*** 兴趣爱好*/@Value("${userinfo.hobbys}")private String[] hobbys;/*** 备注信息*/@Value("${userinfo.blog-remark}")private String blogRemark;//省略getter与setter方法...}

编写测试方法,获取用户YAML配置信息。

import com.pjb.properties.UserProperties;import org.junit.jupiter.api.AfterEach;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import java.util.Arrays;/*** 用户配置测试类* @author pan_junbiao**/@SpringBootTestpublic class UserTest{@Autowiredprivate UserProperties userProperties;/*** 获取用户YAML配置信息* @author pan_junbiao*/@Testpublic void getUserProperties(){System.out.println("获取application.yml配置文件中的信息:");System.out.println("用户编号:" + userProperties.getUserId());System.out.println("用户名称:" + userProperties.getUserName());System.out.println("博客地址:" + userProperties.getBlogUrl());System.out.println("兴趣爱好:共" + userProperties.getHobbys().length + "个," + Arrays.toString(userProperties.getHobbys()));System.out.println("备注信息:" + userProperties.getBlogRemark());}}

执行结果:

2、方法二:使用@ConfigurationProperties注解

示例:修改 UserProperties类(用户配置信息类),使用@ConfigurationProperties注解处理配置文件中以 “userinfo” 为前缀的配置项的值,以装载配置文件的信息。

package com.pjb.properties;import org.springframework.boot.context.properties.ConfigurationProperties;import org.ponent;/*** 用户配置信息类* @author pan_junbiao**/@Component@ConfigurationProperties(prefix = "userinfo")public class UserProperties{/*** 用户编号*/private int userId;/*** 用户名称*/private String userName;/*** 博客地址*/private String blogUrl;/*** 兴趣爱好*/private String[] hobbys;/*** 备注信息*/private String blogRemark;//省略getter与setter方法...}

代码说明:

@Component注解:声明此类是Spring管理类。

@ConfigurationProperties注解:把同类配置信息自动封装成一个实体类。其属性prefix 代表配置文件中配置项的前缀,如在配置文件中定义的“userinfo”。

还可以把@ConfigurationProperties注解直接定义在@Bean注解里,这时Bean实体类就不需要@Component注解和@ConfigurationProperties注解了,在调用时依然一样调用,如下代码:

@Bean@ConfigurationProperties(prefix = "userinfo")public UserInfo userInfo(){return new UserInfo();}

执行结果:

3、方法三:使用参数的形式

示例:创建RedisConfig.java 文件用于读取application.yml 文件的配置信息。

/*** Redis配置类* @author pan_junbiao**/@Configurationpublic class RedisConfig{/*** Jedis连接池*/@Bean("jedis.pool")@Autowiredpublic JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,@Value("${spring.redis.host}") String host,@Value("${spring.redis.port}") int port){return new JedisPool(config, host, port);}/*** Jedis连接池配置信息*/@Bean(name = "jedis.pool.config")public JedisPoolConfig jedisPoolConfig(@Value("${spring.redis.jedis.pool.max-active}") int maxActive,@Value("${spring.redis.jedis.pool.max-wait}") Duration maxWait,@Value("${spring.redis.jedis.pool.max-idle}") int maxIdle,@Value("${spring.redis.jedis.pool.min-idle}") int minIdle){JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();//连接池最大连接数(使用负值表示没有限制)jedisPoolConfig.setMaxTotal(maxActive);//连接池最大阻塞等待时间(使用负值表示没有限制)jedisPoolConfig.setMaxWaitMillis(maxWait.toMillis());//连接池中的最大空闲连接jedisPoolConfig.setMaxIdle(maxIdle);//连接池中的最小空闲连接jedisPoolConfig.setMinIdle(minIdle);return jedisPoolConfig;}}

4、综合实例

实例:在application.yml 配置文件中配置 Redis 信息,创建RedisConfig.java 类(Redis配置类),初始化 Redis 服务。

(1)在application.yml 配置文件中配置 Redis 信息。

spring:redis:database: 0 #Redis数据库索引(默认为0)host: 127.0.0.1 #Redis服务器地址port: 6379 #Redis服务器连接端口password: #Redis服务器连接密码(默认为空)jedis:pool:max-active: 8 #连接池最大连接数(使用负值表示没有限制)max-wait: -1s #连接池最大阻塞等待时间(使用负值表示没有限制)max-idle: 8 #连接池中的最大空闲连接min-idle: 0 #连接池中的最小空闲连接lettuce:shutdown-timeout: 100ms #关闭超时时间,默认值100ms

(2)创建RedisProperties.java(Redis配置属性类),并使用@Value注解注入配置文件内容,以装载配置文件的信息。

package com.pjb.ems.properties;import org.springframework.beans.factory.annotation.Value;import org.ponent;import java.time.Duration;/*** Redis配置属性类* @author pan_junbiao**/@Componentpublic class RedisProperties{/*** Redis数据库索引*/@Value("${spring.redis.database}")private int database;/*** Redis服务器地址*/@Value("${spring.redis.host}")private String host;/*** Redis服务器连接端口*/@Value("${spring.redis.port}")private int port;/*** Redis服务器连接密码*/@Value("${spring.redis.port}")private String password;/*** 连接池最大连接数*/@Value("${spring.redis.jedis.pool.max-active}")private int maxActive;/*** 连接池最大连接数*/@Value("${spring.redis.jedis.pool.max-wait}")private Duration maxWait;/*** 连接池中的最大空闲连接*/@Value("${spring.redis.jedis.pool.max-idle}")private int maxIdle;/*** 连接池中的最小空闲连接*/@Value("${spring.redis.jedis.pool.min-idle}")private int minIdle;public int getDatabase(){return database;}public void setDatabase(int database){this.database = database;}public String getHost(){return host;}public void setHost(String host){this.host = host;}public int getPort(){return port;}public void setPort(int port){this.port = port;}public String getPassword(){return password;}public void setPassword(String password){this.password = password;}public int getMaxActive(){return maxActive;}public void setMaxActive(int maxActive){this.maxActive = maxActive;}public Duration getMaxWait(){return maxWait;}public void setMaxWait(Duration maxWait){this.maxWait = maxWait;}public int getMaxIdle(){return maxIdle;}public void setMaxIdle(int maxIdle){this.maxIdle = maxIdle;}public int getMinIdle(){return minIdle;}public void setMinIdle(int minIdle){this.minIdle = minIdle;}}

(3)创建RedisConfig.java 类(Redis配置类),初始化 Redis 服务。

/*** Redis配置类* @author pan_junbiao**/@Configurationpublic class RedisConfig{@Autowiredprivate RedisProperties redisProperties;/*** Jedis连接池*/@Bean("jedis.pool")@Autowiredpublic JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config){return new JedisPool(config, redisProperties.getHost(), redisProperties.getPort());}/*** Jedis连接池配置信息*/@Bean(name = "jedis.pool.config")public JedisPoolConfig jedisPoolConfig(){JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();//连接池最大连接数(使用负值表示没有限制)jedisPoolConfig.setMaxTotal(redisProperties.getMaxActive());//连接池最大阻塞等待时间(使用负值表示没有限制)jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWait().toMillis());//连接池中的最大空闲连接jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());//连接池中的最小空闲连接jedisPoolConfig.setMinIdle(redisProperties.getMinIdle());return jedisPoolConfig;}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。