SpringBoot獲取配置參數最簡單常用的兩種方式

一凡碼農 2020-02-21 15:16:08

一、自定義屬性及常量

在開發過程中,我們常常用到的多環境配置文件,常用的有:dev,test,prod,在不同環境下,我們用到的一樣的配置參數,例如:redis,mq,回調接口的url配置。這個情況,我們就需要統一的獲取配置參數的方式。

二、配置文件

application-dev.properties

application-test.properties

application-prod.properties

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

三、通過@value注解來加載配置

定義屬性,通過@Value("${屬性名}")注解來加載對應的配置屬性

@Servicepublic 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讀取配置文件的方式大概有五種,這裏只講到我最常用的兩種。其他三種歡迎關注本賬號,後續更新補充!

0 阅读:40

一凡碼農

簡介:專業分享開發技術知識