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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM