属性配置

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]}
posted @ 2020-04-15 14:09  fly_bk  阅读(171)  评论(0编辑  收藏  举报