zoukankan      html  css  js  c++  java
  • Spring Boot获取配置参数最简单常用的两种方式

    一、自定义属性及常量

    在开发过程中,我们常常用到的多环境配置文件,常用的有:dev,test,prod,在不同环境下,我们用到的一样的配置参数,例如:redis,mq,回调接口的url配置。这个情况,我们就需要统一的获取配置参数的方式。
    

    二、配置文件

    application-dev.properties

    application-test.properties

    application-prod.properties

    
    #mq
    mq.acessKey=
    mq.secretKey=
    
    spring.redis.host=127.0.0.1
    spring.redis.password=
    spring.redis.pool.max-active=100
    spring.redis.pool.max-idle=100
    spring.redis.pool.max-wait=10000
    spring.redis.pool.min-idle=20
    spring.redis.port=6379
    spring.redis.sentinel.master= # Name of Redis server.
    spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
    spring.redis.timeout=10000
    

    三、通过@value注解来加载配置

    定义属性,通过@Value("${属性名}")注解来加载对应的配置属性
    
    
    @Service
    public class RocketMqService {
    	private static final Log log = LogFactory.getLog(RocketMqService.class);
    
    	@Value("${mq.acessKey}")
    	private String mqAccessKey;
    	@Value("${mq.secretKey}")
    	private String mqSecretKey;
    	}
    

    四、通过Properties读取文件的方式

    
        private static void readConfig(){
        	try {
    			Properties p = ResourcesUtil.readResources("redis.properties");
    			ADDR_ARRAY = p.getProperty("spring.redis.host");
    			PASSWORD = p.getProperty("spring.redis.password");
    			PORT = Integer.parseInt(p.getProperty("spring.redis.port"));
    			MAX_ACTIVE = Integer.parseInt(p.getProperty("spring.redis.pool.max-active"));
    			MAX_IDLE = Integer.parseInt(p.getProperty("spring.redis.pool.max-idle"));
    			MAX_WAIT = Integer.parseInt(p.getProperty("spring.redis.pool.max-wait"));
    			TIMEOUT = Integer.parseInt(p.getProperty("spring.redis.timeout"));
    		} catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }
    

    五、总结

    Spring Boot读取配置文件的方式大概有五种,这里只讲到我最常用的两种。其他三种欢迎关注本账号,后续更新补充!
  • 相关阅读:
    面向对象-类与实例化对象
    面向对象-面向对象与面向过程优缺点
    pyCharn文件模板变量
    安装pycrypto以及报错处理
    文件-读、写、追加已经文件操作
    文件-读取与编码检测
    运算-三元运算
    三方工具-sqlacodegen
    函数-生成器之斐波拉契数列
    python内存-fromkeys
  • 原文地址:https://www.cnblogs.com/qinshengfei/p/12341473.html
Copyright © 2011-2022 走看看