Spring boot 讀取properties檔案的四種方式

weixin_33782386發表於2018-09-30

Spring boot 讀取properties檔案的四種方式

  • 方式一
    使用@Value註解
    在application.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;
     }
}
5379182-54cad6c893486678.png
image.png
  • 方式二
    使用Environment
    配置檔案還是原來的配置檔案
@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");
    }
}

結果是一樣的。

  • 方式三
    通過@ConfigurationProperties註解,把對應的屬性編寫對應的配置類
@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();
    }
}

結果同上。

  • 方式四 使用PropertiesLoaderUtils
    首先在resources資料夾下建立app-config.properties檔案
    裡面有兩個屬性
    my.name=zhangsan
    my.old=18

檔案屬性監聽器

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;
    }
}

結果如下:

5379182-8860bd3b05b6ec4c.png
image.png

總結到此結束,若有錯誤或補充可以聯絡我guofei_wu@163.com,謝謝~

相關文章