【Java Web開發學習】Spring加載外部properties配置文件


【Java Web開發學習】Spring加載外部properties配置文件

轉載:https://www.cnblogs.com/yangchongxing/p/9136505.html

1、聲明屬性源,通過Spring的Environment檢索裝配屬性

Environment檢索的值來源於屬性源,直接從Environment中檢索屬性是非常方便的,尤其在Java配置中裝配Bean的時候,。

package com.qq.weixin.mp.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource(value="classpath:weixin.properties")//屬性源,maven配置位於src\main\resources目錄下
public class WeixinConfig {
    private String appid;
    private String appsecret;
    @Autowired
    Environment env;
    @Bean
    public Map<String, String> config() {
        appid = env.getProperty("appid");//檢索屬性
        appsecret = env.getProperty("appsecret");//檢索屬性
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", appid);
        map.put("appsecret", appsecret);
        return map;
    }
}

2、有配置類,通過占位符來裝配屬性

占位符的值來源於屬性源,占位符的形式為使用${...}包裝的屬性名稱。

package com.qq.weixin.mp.config;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value="classpath:weixin.properties")//屬性源
public class WeixinConfig {
    @Value("${appid}")//占位符
    private String appid;
    @Value("${appsecret}")
    private String appsecret;
    @Bean
    public Map<String, String> config() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", appid);
        map.put("appsecret", appsecret);
        return map;
    }
}

 或者定義PropertySourcesPlaceholderConfigurer Bean Spring3.1以后推薦使用

    @Bean
    public PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
<context:property-placeholder />

 


免責聲明!

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



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