zoukankan      html  css  js  c++  java
  • 属性配置

    SpringApplication设置properties

    @SpringBootApplication
    public class SpringBootDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication springApplication = new SpringApplication(SpringBootDemoApplication.class);
            Properties properties = new Properties();
            properties.setProperty("fly.url","fly_url1");
            springApplication.setDefaultProperties(properties);
            springApplication.run(args);
        }
    }
    

    使用@PropertySource

    
    @SpringBootApplication
    @PropertySource({"demo.properties"})//低于application
    public class SpringBootDemoApplication {
        public static void main(String[] args) {
            SpringApplication springApplication = new SpringApplication(SpringBootDemoApplication.class);
            springApplication.run(args);
        }
    }
    

    application.properties

    # 自定义属性  优先于 application.yml
    #fly.url=fly_url2
    

    application.yml

    # 自定义属性
    fly:
      url: fly_url4
    

    application-default.yml

    application-default.properties

    测试

    import org.springframework.boot.CommandLineRunner;
    import org.springframework.context.EnvironmentAware;
    import org.springframework.core.env.Environment;
    import org.springframework.stereotype.Component;
    
    /**
     * 启动器加载属性配置
     */
    @Component
    public class ResultCommandLineRunner implements
            CommandLineRunner, EnvironmentAware {
        private Environment environment;
        @Override
        public void run(String... args) throws Exception {
            System.out.println(environment.getProperty("fly.url"));
            System.out.println(environment.getProperty("fly.avg.age"));
        }
    
        @Override
        public void setEnvironment(Environment environment) {
            this.environment = environment;
        }
    }
    

    springboot测试中定义

    //@SpringBootTest(properties = {"fly.url=fly_url9"})
    @SpringBootTest
    @TestPropertySource({"classpath:demo.properties"})
    public class Pro {
    
        @Test
        public void test(){
        }
    }
    

    可使用动态变量

    fly.avg.age=${random.int[20,30]}
    
  • 相关阅读:
    学习java随笔第五篇:流程控制
    学习java随笔第四篇:运算符
    学习java随笔第三篇:java的基本数据类型
    知识精简
    性能优化(详细)
    2,8,10,16进制转换
    前端优化35例
    性能优化
    字面量自定义事件

  • 原文地址:https://www.cnblogs.com/fly-book/p/12704917.html
Copyright © 2011-2022 走看看