• spring boot 读书笔记4Spring Boot中的项目属性配置


    1.少量配置信息的情形

    application.yml 中配置微服务地址

    url:
      orderUrl: http://localhost:8002
    

      

    通过@value获取

    @RestController
    @RequestMapping("/test")
    public class TestController {
        @Value("${url.orderUrl}")
        private String orderUrl;
        @RequestMapping("/config")
        public String testConfig(){
            return orderUrl;
        }
    
    }
    

      

    2. 多个配置信息的情形

    多个配置信息的情形,

    application.yml

    url:
      orderUrl: http://localhost:8002
      testUrl: http://127.0.0.1:88/test
      devUrl: http://127.0.0.1:8811/dev
    

      

    pom.xml引入

    <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
    

      

    编写实体类

    需要加ConfigurationProperties,prefix指向配置,@Component,把该类作为组件放到Spring容器中

    @Component
    @ConfigurationProperties(prefix ="url")
    public class MicroServiceUrl {
        private String orderUrl;
        private String testUrl;
        private String devUrl;
    
        public void setDevUrl(String devUrl) {
            this.devUrl = devUrl;
        }
    
        public String getDevUrl() {
            return devUrl;
        }
    
        public String getOrderUrl() {
            return orderUrl;
        }
    
        public void setOrderUrl(String orderUrl) {
            this.orderUrl = orderUrl;
        }
    
        public String getTestUrl() {
            return testUrl;
        }
    
        public void setTestUrl(String testUrl) {
            this.testUrl = testUrl;
        }
    }
    

      

    通过@Resource 将写好的配置类注入进来

    @RestController
    @RequestMapping("/test")
    public class TestController {
        @Resource
        private MicroServiceUrl microServiceUrl;
        @RequestMapping("/order")
        public String orderConfig(){
            return microServiceUrl.getOrderUrl();
        }
        @RequestMapping("/test")
        public String testConfig(){
            return microServiceUrl.getTestUrl();
        }
        @RequestMapping("/dev")
        public String devConfig(){
            return microServiceUrl.getDevUrl();
        }
    

      

    3. 指定项目配置文件

    两个配置文件,配置不同环境

    application-dev.yml

    application-pro.yml

    application.yml指定选用哪个即可

    spring:
      profiles:
        active:
        - dev
    

      

  • 相关阅读:
    Python运算符,基本数据类型
    Python2 错误记录1File "<string>", line 1, in <module> NameError: name 'f' is not defined
    用户登录三次练习
    跟我一起学Python-day1(条件语句以及初识变量)
    vim operation
    步步为营-28-事件本质
    步步为营-27-事件
    步步为营-26-多播委托
    步步为营-25-委托(比大小)
    步步为营-24-委托
  • 原文地址:https://www.cnblogs.com/fczlm/p/15949985.html
Copyright © 2020-2023  润新知