首页 > 编程语言 > 详细

【Java Web开发学习】Spring加载外部properties配置文件

时间:2018-06-05 00:25:13      阅读:254      评论:0      收藏:0      [点我收藏+]

【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")//属性源
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;
    }
}

 

【Java Web开发学习】Spring加载外部properties配置文件

原文:https://www.cnblogs.com/yangchongxing/p/9136505.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!