Spring boot 读取properties文件的四种方式

2018-09-30  本文已影响117人  Mason啊

Spring boot 读取properties文件的四种方式

my.name=lisi
my.old=19

在代码中使用

@RestController
@RequestMapping(value = "/my")
public class MyController {
    @Value("${my.name}")
    private String name;
    @Value("${my.old}")
    private int old;

    @RequestMapping(value = "/test3")
     public String test3() {
         return "my name is " + name + "---" + old;
     }
}
image.png
@RestController
@RequestMapping(value = "/my")
public class MyController {    
    @Autowired
    private Environment env;

    @RequestMapping(value = "/test5")
    public String test5() {
        return "my name is " + env.getProperty("my.name") + " --" + env.getProperty("my.old");
    }
}

结果是一样的。

@Component
@ConfigurationProperties(prefix = "my")
public class PropertiesConfig {
    private String name;
    private int old;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getOld() {
        return old;
    }

    public void setOld(int old) {
        this.old = old;
    }
}
@RestController
@RequestMapping(value = "/my")
@ConfigurationProperties(prefix = "my")
public class MyController {  
    private String name;
    private int old;
    @Autowired
    private PropertiesConfig  config;

    @RequestMapping(value = "/test4")
    public String test4() {
        return "my name is " + config.getName() + config.getOld();
    }
}

结果同上。

文件属性监听器

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

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

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

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

public class PropertiesListenerConfig {
    public static Map 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 {
                // 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<String, String> getAllProperty() {
        return propertiesMap;
    }
}

编写完成之后需要在项目启动的时候注册监听器,修改启动的main函数

public static void main(String[] args) {
        SpringApplication application = new SpringApplication(DemoSpringbootApplication.class);
        // 第四种方式:注册监听器
        application.addListeners(new PropertiesListener("app-config.properties"));
        application.run(args);
}

控制器类

@RestController
@RequestMapping(value = "/my")
public class MyController {    
    @RequestMapping("/test6")
    public Map<String, Object> test6() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.putAll(PropertiesListenerConfig.getAllProperty());
        return map;
    }
}

结果如下:

image.png
总结到此结束,若有错误或补充可以联系我guofei_wu@163.com,谢谢~
上一篇下一篇

猜你喜欢

热点阅读