case1. 通过注解的方式读取配置 24.Externalized Configuration
application.properties文件新增配置
externalized.configuration=extConfigSampleVal
控制层代码(仅做示例用,不作为推荐写法)
@RestController public class GreetingController { @Value("${externalized.configuration}") private String extConfig; private static final String template = "Hello, %s!"; private final AtomicLong counter = new AtomicLong(); @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, extConfig)); } }
*通过@Value注解将配置赋值到所注解的变量
访问host/greeting
case2.JAVA BEAN的方式读取配置
java bean:
@ConfigurationProperties(prefix="my") @Component public class Config { private int port; private List<String> servers = new ArrayList<String>(); //getter,setter }
读取代码
@Autowired private Config config; @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, config.getPort())); }
自动注入Config实例,测试结果:
case3.区分环境读取不同的配置文件 24.4 Profile-specific Properties
新建3个配置文件分别对应开发环境dev,测试环境sit,生产环境prod
三个文件各自添加自己的变量做测试用:
application.properties设置配置指定要读取的配置文件,相关属性spring.profiles.active
这里将以application-{profile}.properties的格式查找对应配置文件,这里将使用application-dev.properties
编辑控制层代码
@Value("${currentEnv}") private String currentEnv; @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, currentEnv)); }
访问host/greeting
case4.占位符
app.name=MyApp app.description=${app.name} is a Spring Boot application
@Value("${app.description}") private String appDesc; @RequestMapping("/greeting") public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) { return new Greeting(counter.incrementAndGet(), String.format(template, appDesc)); }
case5.随机值
my.secret=${random.value} my.number=${random.int} my.bignumber=${random.long} my.uuid=${random.uuid} my.number.less.than.ten=${random.int(10)} my.number.in.range=${random.int[1024,65536]}
返回