SpringBoot 4種類のpropertiesファイルを読み込む方法

28553 ワード

前言


プロジェクト開発ではプロファイルが頻繁に使用され、プロファイルの存在によって大きな重複作業が解決されます.今日はSpringbootでプロファイルを取得する方法を4つ共有します.
注意:最初の3つのテストプロファイルはspringbootのデフォルトのアプリケーションです.propertiesファイル
####################### #########################
com.zyd.type3=Springboot - @ConfigurationProperties
com.zyd.title3= @ConfigurationProperties 
#map
com.zyd.login[username]=zhangdeshuai
com.zyd.login[password]=zhenshuai
com.zyd.login[callback]=http://www.flyat.cc
#list
com.zyd.urls[0]=http://ztool.cc
com.zyd.urls[1]=http://ztool.cc/format/js
com.zyd.urls[2]=http://ztool.cc/str2image
com.zyd.urls[3]=http://ztool.cc/json2Entity
com.zyd.urls[4]=http://ztool.cc/ua

####################### #########################
com.zyd.type=Springboot - @Value
com.zyd.title= @Value 

####################### #########################
com.zyd.type2=Springboot - Environment
com.zyd.title2= Environment 

一、@ConfigurationProperties方式


カスタム構成クラス:PropertiesConfig.java
package com.zyd.property.config;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
//import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 *  
 * @author yadong.zhang
 * @date 2017 6 1   4:34:18 
 * @version V1.0
 * @since JDK : 1.7
 */
@Component
@ConfigurationProperties(prefix = "com.zyd")
// PropertySource application.properties
// @PropertySource(value = "config.properties")
public class PropertiesConfig {

    public String type3;
    public String title3;
    public Map login = new HashMap();
    public List urls = new ArrayList<>();

    public String getType3() {
        return type3;
    }

    public void setType3(String type3) {
        this.type3 = type3;
    }

    public String getTitle3() {
        try {
            return new String(title3.getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return title3;
    }

    public void setTitle3(String title3) {
        this.title3 = title3;
    }

    public Map getLogin() {
        return login;
    }

    public void setLogin(Map login) {
        this.login = login;
    }

    public List getUrls() {
        return urls;
    }

    public void setUrls(List urls) {
        this.urls = urls;
    }

} 

プログラム起動クラス:Applaction.java
package com.zyd.property;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zyd.property.config.PropertiesConfig;

/**
 * @author yadong.zhang
 * @date 2017 6 1   3:49:30 
 * @version V1.0
 * @since JDK : 1.7
 */
@SpringBootApplication
@RestController
public class Applaction {

    @Autowired
    private PropertiesConfig propertiesConfig;

    /**
     * 
     *  : `@ConfigurationProperties` 
     * 
     * @author zyd
     * @throws UnsupportedEncodingException
     * @since JDK 1.7
     */
    @RequestMapping("/config")
    public Map configurationProperties() {
        Map map = new HashMap();
        map.put("type", propertiesConfig.getType3());
        map.put("title", propertiesConfig.getTitle3());
        map.put("login", propertiesConfig.getLogin());
        map.put("urls", propertiesConfig.getUrls());
        return map;
    }

    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(Applaction.class);
        application.run(args);
    }
}

アクセス結果:
{"title":" @ConfigurationProperties ","urls":["http://ztool.cc","http://ztool.cc/format/js","http://ztool.cc/str2image","http://ztool.cc/json2Entity","http://ztool.cc/ua"],"login":{"username":"zhangdeshuai","callback":"http://www.flyat.cc","password":"zhenshuai"},"type":"Springboot - @ConfigurationProperties"}

二、@Value注記方式を使用する


プログラム起動クラス:Applaction.java

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yadong.zhang
 * @date 2017 6 1   3:49:30 
 * @version V1.0
 * @since JDK : 1.7
 */
@SpringBootApplication
@RestController
public class Applaction {

    @Value("${com.zyd.type}")
    private String type;

    @Value("${com.zyd.title}")
    private String title;

    /**
     * 
     *  : `@Value("${propertyName}")` 
     * 
     * @author zyd
     * @throws UnsupportedEncodingException
     * @since JDK 1.7
     */
    @RequestMapping("/value")
    public Map value() throws UnsupportedEncodingException {
        Map map = new HashMap();
        map.put("type", type);
        // *.properties ISO-8859-1 , 
        map.put("title", new String(title.getBytes("ISO-8859-1"), "UTF-8"));
        return map;
    }

    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(Applaction.class);
        application.run(args);
    }
}

アクセス結果:
{"title":" @Value ","type":"Springboot - @Value"}

三、Environmentの使用


プログラム起動クラス:Applaction.java
package com.zyd.property;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author yadong.zhang
 * @date 2017 6 1   3:49:30
 * @version V1.0
 * @since JDK : 1.7
 */
@SpringBootApplication
@RestController
public class Applaction {

    @Autowired
    private Environment env;

    /**
     * 
     *  : `Environment`
     * 
     * @author zyd
     * @throws UnsupportedEncodingException
     * @since JDK 1.7
     */
    @RequestMapping("/env")
    public Map env() throws UnsupportedEncodingException {
        Map map = new HashMap();
        map.put("type", env.getProperty("com.zyd.type2"));
        map.put("title", new String(env.getProperty("com.zyd.title2").getBytes("ISO-8859-1"), "UTF-8"));
        return map;
    }

    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(Applaction.class);
        application.run(args);
    }
}

アクセス結果:
{"title":" Environment ","type":"Springboot - Environment"}

四、PropertiesLoaderUtilsの使用


app-config.properties
####  (`Listeners`) + `PropertiesLoaderUtils` 
com.zyd.type=Springboot - Listeners
com.zyd.title= Listeners + PropertiesLoaderUtils 
com.zyd.name=zyd
com.zyd.address=Beijing
com.zyd.company=in

PropertiesListener.JAvaはロードプロファイルを初期化するために使用されます
package com.zyd.property.listener;

import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;

import com.zyd.property.config.PropertiesListenerConfig;

/**
 *  , 
 * 
 * @author @gmail.com">yadong.zhang
 * @date 2017 6 1   3:38:25 
 * @version V1.0
 * @since JDK : 1.7
 */
public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {

    private String propertyFileName;

    public PropertiesListener(String propertyFileName) {
        this.propertyFileName = propertyFileName;
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        PropertiesListenerConfig.loadAllProperties(propertyFileName);
    }
}

PropertiesListenerConfig.JAvaプロファイルの内容のロード
package com.zyd.property.config;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.core.io.support.PropertiesLoaderUtils;

/**
 *  :PropertiesLoaderUtils
 * 
 * @author yadong.zhang
 * @date 2017 6 1   3:32:37
 * @version V1.0
 * @since JDK : 1.7
 */
public class PropertiesListenerConfig {
    public static Map propertiesMap = new HashMap<>();

    private static void processProperties(Properties props) throws BeansException {
        propertiesMap = new HashMap();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            try {
                // PropertiesLoaderUtils ISO-8859-1, 
                propertiesMap.put(keyStr, new String(props.getProperty(keyStr).getBytes("ISO-8859-1"), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (java.lang.Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void loadAllProperties(String propertyFileName) {
        try {
            Properties properties = PropertiesLoaderUtils.loadAllProperties(propertyFileName);
            processProperties(properties);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }

    public static Map getAllProperty() {
        return propertiesMap;
    }
}

Applaction.JAva起動クラス
package com.zyd.property;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zyd.property.config.PropertiesListenerConfig;
import com.zyd.property.listener.PropertiesListener;

/**
 * @author yadong.zhang
 * @date 2017 6 1   3:49:30 
 * @version V1.0
 * @since JDK : 1.7
 */
@SpringBootApplication
@RestController
public class Applaction {
    /**
     * 
     *  : (`Listeners`) + `PropertiesLoaderUtils` 
     * 
     * @author zyd
     * @throws UnsupportedEncodingException
     * @since JDK 1.7
     */
    @RequestMapping("/listener")
    public Map listener() {
        Map map = new HashMap();
        map.putAll(PropertiesListenerConfig.getAllProperty());
        return map;
    }

    public static void main(String[] args) throws Exception {
        SpringApplication application = new SpringApplication(Applaction.class);
        //  : 
        application.addListeners(new PropertiesListener("app-config.properties"));
        application.run(args);
    }
}

アクセス結果:
{"com.zyd.name":"zyd","com.zyd.address":"Beijing","com.zyd.title":" Listeners + PropertiesLoaderUtils ","com.zyd.type":"Springboot - Listeners","com.zyd.company":"in"}

作者:慕冬雪リンク:http://www.imooc.com/article/18252出典:慕課網