美文网首页
Spring boot 读取properties文件的四种方式

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

作者: Mason啊 | 来源:发表于2018-09-30 15:46 被阅读117次

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

    结果如下:

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

    相关文章

      网友评论

          本文标题:Spring boot 读取properties文件的四种方式

          本文链接:https://www.haomeiwen.com/subject/qdswoftx.html