Four ways to read the properties file in SpringBoot

Keywords: Java JDK SpringBoot Spring

preface

Configuration files are often used in project development. The existence of configuration files solves a lot of repeated work. Today, I'll share four ways to get configuration files in spring boot.

Note: the first three test configuration files are spring boot default application.properties file

#######################Mode 1#########################
com.zyd.type3=Springboot - @ConfigurationProperties
com.zyd.title3=use@ConfigurationProperties Get profile
#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

#######################Mode 2#########################
com.zyd.type=Springboot - @Value
com.zyd.title=use@Value Get profile

#######################Mode 3#########################
com.zyd.type2=Springboot - Environment
com.zyd.title2=use Environment Get profile

1, @ ConfigurationProperties mode

Custom configuration class: 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;

/**
 * Corresponds to the first segment of the configuration file above
 * @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>
 * @date 2017 4:34:18 p.m., June 1, 2006 
 * @version V1.0
 * @since JDK :  1.7
 */
@Component
@ConfigurationProperties(prefix = "com.zyd")
// PropertySource defaults to application.properties
// @PropertySource(value = "config.properties")
public class PropertiesConfig {

    public String type3;
    public String title3;
    public Map<String, String> login = new HashMap<String, String>();
    public List<String> 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<String, String> getLogin() {
        return login;
    }

    public void setLogin(Map<String, String> login) {
        this.login = login;
    }

    public List<String> getUrls() {
        return urls;
    }

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

} 

Program start class: 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 <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>
 * @date 2017 3:49:30 p.m., June 1, 2010 
 * @version V1.0
 * @since JDK :  1.7
 */
@SpringBootApplication
@RestController
public class Applaction {

    @Autowired
    private PropertiesConfig propertiesConfig;

    /**
     * 
     * The first way: use the '@ ConfigurationProperties' annotation to inject the profile properties into the configuration object class
     * 
     * @author zyd
     * @throws UnsupportedEncodingException
     * @since JDK 1.7
     */
    @RequestMapping("/config")
    public Map<String, Object> configurationProperties() {
        Map<String, Object> map = new HashMap<String, Object>();
        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);
    }
}

Results:

{"title":"use@ConfigurationProperties Get profile","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"}

2, Use @ Value annotation method

Program start class: 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 <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>
 * @date 2017 3:49:30 p.m., June 1, 2010 
 * @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;

    /**
     * 
     * The second way is to use '@ Value("${propertyName}")' annotation
     * 
     * @author zyd
     * @throws UnsupportedEncodingException
     * @since JDK 1.7
     */
    @RequestMapping("/value")
    public Map<String, Object> value() throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", type);
        // *The Chinese in the. properties file is encoded by ISO-8859-1 by default, so the Chinese content needs to be recoded
        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);
    }
}

Results:

{"title":"use@Value Get profile","type":"Springboot - @Value"}

3, Using Environment

Program start class: 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 <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>
 * @date 2017 3:49:30 p.m., June 1, 2010
 * @version V1.0
 * @since JDK :  1.7
 */
@SpringBootApplication
@RestController
public class Applaction {

    @Autowired
    private Environment env;

    /**
     * 
     * Third way: use ` Environment`
     * 
     * @author zyd
     * @throws UnsupportedEncodingException
     * @since JDK 1.7
     */
    @RequestMapping("/env")
    public Map<String, Object> env() throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<String, Object>();
        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);
    }
}

Results:

{"title":"use Environment Get profile","type":"Springboot - Environment"}

4, Using PropertiesLoaderUtils

app-config.properties

#### By registering listeners + propertiesloaderutils
com.zyd.type=Springboot - Listeners
com.zyd.title=use Listeners + PropertiesLoaderUtils Get profile
com.zyd.name=zyd
com.zyd.address=Beijing
com.zyd.company=in

PropertiesListener.java Used to initialize the load profile

package com.zyd.property.listener;

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

import com.zyd.property.config.PropertiesListenerConfig;

/**
 * Profile listener, used to load custom profiles
 * 
 * @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>
 * @date 2017 3:38:25 p.m., June 1, 2010 
 * @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);
    }
}

Prop ertiesListenerConfig.java Load profile content

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;

/**
 * Fourth way: PropertiesLoaderUtils
 * 
 * @author <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>
 * @date 2017 3:32:37 PM, June 1, 2006
 * @version V1.0
 * @since JDK :  1.7
 */
public class PropertiesListenerConfig {
    public static Map<String, String> propertiesMap = new HashMap<>();

    private static void processProperties(Properties props) throws BeansException {
        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            try {
                // The default encoding of PropertiesLoaderUtils is ISO-8859-1, which can be transcoded here
                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<String, String> getAllProperty() {
        return propertiesMap;
    }
}

Applaction.java Startup class

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 <a href="mailto:yadong.zhang0415@gmail.com">yadong.zhang</a>
 * @date 2017 3:49:30 p.m., June 1, 2010 
 * @version V1.0
 * @since JDK :  1.7
 */
@SpringBootApplication
@RestController
public class Applaction {
    /**
     * 
     * The fourth way: by registering listeners + propertiesloaderutils
     * 
     * @author zyd
     * @throws UnsupportedEncodingException
     * @since JDK 1.7
     */
    @RequestMapping("/listener")
    public Map<String, Object> listener() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.putAll(PropertiesListenerConfig.getAllProperty());
        return map;
    }

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

Results:

{"com.zyd.name":"zyd","com.zyd.address":"Beijing","com.zyd.title":"use Listeners + PropertiesLoaderUtils Get profile","com.zyd.type":"Springboot - Listeners","com.zyd.company":"in"}

Author: Mu Dongxue
Link: http://www.imooc.com/article/18252
Source: mooc.com

Posted by shaneiadt on Sun, 31 May 2020 07:32:08 -0700