一、自定義屬性及常量
在開發過程中,我們常常用到的多環境配置文件,常用的有: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讀取配置文件的方式大概有五種,這里只講到我最常用的兩種。其他三種歡迎關注本賬號,后續更新補充!