zoukankan      html  css  js  c++  java
  • 企业分布式微服务云SpringCloud SpringBoot mybatis (十九)Spring Boot 自定义配置文件

    上面介绍的是我们都把配置文件写到application.yml中。有时我们不愿意把配置都写到application配置文件中,这时需要我们自定义配置文件,比如test.properties:

    com.forezp.name=forezp
    com.forezp.age=12
    

      

    怎么将这个配置文件信息赋予给一个javabean呢?

    @Configuration
    @PropertySource(value = "classpath:test.properties")
    @ConfigurationProperties(prefix = "com.forezp")
    public class User {
        private String name;
        private int age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    }
    

      

    在最新版本的springboot,需要加这三个注解。

    @Configuration 
    @PropertySource(value = “classpath:test.properties”) 
    @ConfigurationProperties(prefix = “com.forezp”);在1.4版本需要 
    PropertySource加上location。
    
    @RestController
    @EnableConfigurationProperties({ConfigBean.class,User.class})
    public class LucyController {
        @Autowired
        ConfigBean configBean;
    
        @RequestMapping(value = "/lucy")
        public String miya(){
            return configBean.getGreeting()+" >>>>"+configBean.getName()+" >>>>"+ configBean.getUuid()+" >>>>"+configBean.getMax();
        }
    
        @Autowired
        User user;
        @RequestMapping(value = "/user")
        public String user(){
            return user.getName()+user.getAge();
        }
    
    }
    

      

    启动工程,打开localhost:8080/user;浏览器会显示:

    forezp12

    四、多个环境配置文件

    在现实的开发环境中,我们需要不同的配置环境;格式为application-{profile}.properties,其中{profile}对应你的环境标识,比如:

    • application-test.properties:测试环境
    • application-dev.properties:开发环境
    • application-prod.properties:生产环境

    怎么使用?只需要我们在application.yml中加:

    spring:
      profiles:
        active: dev
    

      

    其中application-dev.yml:

     server:
      port: 8082
    

      

    启动工程,发现程序的端口不再是8080,而是8082。

    源码来源

  • 相关阅读:
    css 样式 图片平铺整个界面
    div垂直居中 css div盒子上下垂直居中
    .net 日期格式转换
    一个DIV三列布局100%高度自适应的好例子(国外)
    TFS2012团队管理基本配置及基础使用方法
    转-CSS3 圆角(border-radius)
    webpack进阶用法你都get到了么?
    webpack4的配置你都掌握了么?
    初入webpack
    番外篇:一篇读懂浏览器结构
  • 原文地址:https://www.cnblogs.com/Abbie/p/8440674.html
Copyright © 2011-2022 走看看