Article From:https://www.cnblogs.com/yangchongxing/p/9136505.html

【Java WebDeveloping learning] Spring loading external properties configuration files

Reprint: https://www.cnblogs.com/yangchongxing/p/9136505.html

1、Declaring the attribute source, retrieving through the Spring’s EnvironmentcomeAssembly attributes

EnvironmentRetrieving values are derived from attribute sources. Retrieving attributes directly from Environment is very convenient, especially when Bean is assembled in Java configuration.

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")//Attribute sourcepublic class WeixinConfig {
    private String appid;
    private String appsecret;
    @Autowired
    Environment env;
    @Bean
    public Map<String, String> config() {
        appid = env.getProperty("appid");//Retrieval attribute
        appsecret = env.getProperty("appsecret");//Retrieval attribute
        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", appid);
        map.put("appsecret", appsecret);
        return map;
    }
}

2、Declare property sources, assemble attributes by placeholders

The value of placeholder comes from the attribute source. The placeholder is in the form of the name of the attribute wrapped with $}}.

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")//Attribute source
public class WeixinConfig {
    @Value("${appid}")//placeholder
    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;
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *