zoukankan      html  css  js  c++  java
  • Springboot 获取yml、properties参数

    获取properties或yml文件的配置数据(两种方法)(默认的application文件或者自定义的yml和properties)

    1、使用@Value()注解
    1.1 配置数据
    如:在properties.yml文件配置如下数据
        message_zh: 张三
        message_en: ergouzi
    在controller中获取:
    1.2 读取数据
    读取自定义文件:须加注解
    @PropertySource(value = {"classpath:config.yml","classpath:config.properties"})

     读取application文件不需要加注解
    // 中文
    @Value("${message_zh}")
    private String message_zh;
    // 英文
    @Value("${message_en}")
    private String message_en;
    
    @RequestMapping(value = "/{id}")
    public String index(HttpServletRequest request, @PathVariable Integer id){
        if (id == 1 ){
            request.setAttribute("info",message_zh);
        }else {
            request.setAttribute("info", message_en);
        }
        return "index";
    }

     2、使用 @component
        @ConfigurationProperties(prefix = "user")
        @PropertySource(value = "classpath:myConfig.properties")

    首先在myConfig.properties或myConfig.yml中配置参数:
        user.userName = '李二狗'
        user.password = 'admin'
    
    2.1 javabean
    /**
     * 〈一句话功能简述〉<br> 
     * 〈yml或properties配置参数〉
     *
     * @author 丶Zh1Guo
     * @create 2018/11/21
     * @since 1.0.0
     */
    @Component                                // 组件
    @ConfigurationProperties(prefix = "user")              // 前缀
    @PropertySource(value = "classpath:myConfig.properties")    // 自定义配置文件路径
    public class properConfig {
        private String userName;   // 注意要和配置文件一致
        private String password;
    
        public String getUserName() {
            return userName;
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    2.2 controller
    /**
     * 〈一句话功能简述〉<br> 
     * 〈〉
     *
     * @author 丶Zh1Guo
     * @create 2018/11/21
     * @since 1.0.0
     */
    @restController
    public class template {
        @Autowired
        properConfig config;
    
        @RequestMapping(value = "/config")
        public String config(){
            return config.getUserName();
        }
    }

    总结:

    第一种方法适合只取某些数据

    第二种方法适合取所有数据

    yml和properties区别

    yml:    key:(空格)value

    properties: key = value

     

  • 相关阅读:
    Oracle学习笔记:在ubuntu 8.10 Sever上 安装oracle10g,真真正正简简单单的解决‘utilities ctx_on‘错误
    Oracle学习笔记:oracle服务在linux平台的启动问题
    非常酷的 Javascript 简单调试工具Blackbird
    【转】Smashing Magazine CSS3 设计赛获奖作品
    Windows7 IIS7下以FastCgi和ISAPI方法安装配置PHP5教程
    推荐60多个CSS GALLERY画廊网站
    【转】2010全球最值得模仿的230个网站
    Godaddy免费空间WordPress使用记录
    【转】浅谈大型网站动态应用系统架构
    你可能不知道的10个JavaScript小技巧
  • 原文地址:https://www.cnblogs.com/wangzh1guo/p/9995248.html
Copyright © 2011-2022 走看看