获取配置文件中的属性
开发过程中,配置一般放在独立的配置文件中,而不会在代码中写死,这样做的目的主要是便于修改调整。如何从配置文件中读取相关配置内容呢?
- 通过ResourceBundle类进行
ResourceBundle rb = ResourceBundle.getBundle("application"); String secret = rb.getString("system.app.appSecret");
- 通过ClassPathResource + Properties 进行
ClassPathResource resource = new ClassPathResource("application.properties"); Properties properties = PropertiesLoaderUtils.loadProperties(resource); String secret = properties.getProperty("system.app.Secret");
- 通过@Value注解
package com.app.warehouse.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; /** * @Author author * @Date 2022/8/20 11:35 上午 */ @Component public class ApplicationConfig { @Value("${system.app.appSecret}") public String appSecret; @Value("${system.app.clientSession}") public String clientSession; public String getAppSecret() { return appSecret; } public void setAppSecret(String appSecret) { this.appSecret = appSecret; } public String getClientSession() { return clientSession; } public void setClientSession(String clientSession) { this.clientSession = clientSession; } }
- 待续...