spring讀取配置文件的屬性

1.使用@Value(“${XXX.XXX}”)

(1)spring 默認讀取application.yml(或properties),直接使用@Value 註解即可,

例如:

@Value("${token.valid-time:30}")  :30表示配置文件未獲取到值時,使用默認值30
protected  Integer idTokenValidTime;

(2)讀取自定義配置文件定義屬性

添加類註解

@ConfigurationProperties(prefix = "token") //指定前綴,使用@Value 不指定應該也行,未測試過
@PropertySource(value = { "classpath:token-config.yml" })//指定自定義配置文件的位置、名字,這裏默認在resource下面

具體使用見(1)

2.使用@PropertySource,並將配置文件屬性自動對應帶類屬性

@Component
@Data
@ConfigurationProperties(prefix = "test")
//指定配置文件路徑、名字---爲獲取到的值忽略掉,---指定編碼格式,防止獲取的內容亂碼,特別是中文。
@PropertySource(value = "classpath:test.properties", ignoreResourceNotFound = true, encoding = "UTF-8")
public class CommonTest {
private String name;
private String id;
}

配置文件內容:

test.name=123

spring 會自動將配置文件的屬性讀取到這個類中,並封裝爲一個bean,使用時直接用@Autowired注入即可,bean的名字默認爲類名,首字母小寫。

如上,bean裏面只有name=123,id=null

3.直接使用${XXX}獲取

例如:

@RequestMapping("${managerPath}/ap_resource"),

配置文件:

managerPath: /console

注意:@RequestMapping指定的路徑是會繼承的!!!

4.自定義加載

(1)方法一未測試

<1>private static String[] errConfigFiles = new String[]{"errors.properties"};
<2>PropertiesLoader propertiesLoader = new PropertiesLoader(errConfigFiles);

 <3> String value = propertiesLoader.getString(XXX);

(2)方法2 自定義key-value ,

使用ResourceLoader 加載到內存中,使用時,根據code值從內存中讀取

public class ResponseDefaultMsg {
    private static final String msgCodeFileName = "msg-code-file.yml";

    private static Properties properties;

    public Properties getProperties() {
        return properties;
    }

    /**
     * 加載配置文件的屬性
     *
     * @param location
     * @return
     */
    public static void loadProperties(String location) {
        ResourceLoader loder = new PathMatchingResourcePatternResolver();
        Resource resource = loder.getResource(location);
        properties = new Properties();
        try {
            //防止中文亂碼
           // EncodedResource encodedResource=new EncodedResource(resource,"UTF-8");
            //InputStream inputStream = encodedResource.getInputStream();
            /**
             * 主要是properties.load 加載時亂碼,reader 是可以指定字符集的,並且默認utf-8
             */
            properties.load(new InputStreamReader(resource.getInputStream()));
            //properties.load(inputStream);
          //  System.out.println(properties);
        } catch (IOException io) {
            log.error("Could not load properties from path:" + location + io.getMessage());
        }
    }

    /**
     * 獲取默認信息
     *
     * @param code
     * @return
     */
    public static String getDefaultMsg(Integer code) {
        if (properties == null) {
            loadProperties(msgCodeFileName);
        }
        if (properties != null) {
            return properties.getProperty(code.toString());
        } else {
            return null;
        }
    }

}

詳細代碼請移步我的github畢設項目:

https://github.com/CorbinY/tingjian-back-api

配置類在tingjian-back-api/common/src/main/java/org/corbin/common/base/Response/包中

 

碼字西褲,覺得不錯請點個贊,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章