- 基本属性配置
server:
port: 8081
servlet:
context-path: /luckymoney
- 类对象属性配置
limit:
minMoney: 0.01
maxMoney: 999
description: 最少发${limit.minMoney}元,最多发${limit.maxMoney}元
package com.zyl.luckymoney.beans;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Component
@ConfigurationProperties(prefix = "limit")
public class LimitConfiguration {
private BigDecimal minMoney;
private BigDecimal maxMoney;
private String description;
public BigDecimal getMinMoney() {
return minMoney;
}
public void setMinMoney(BigDecimal minMoney) {
this.minMoney = minMoney;
}
public BigDecimal getMaxMoney() {
return maxMoney;
}
public void setMaxMoney(BigDecimal maxMoney) {
this.maxMoney = maxMoney;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
- 多环境运行
通过java -jar -Dspring.profiles.active=prod target/luckymoney-0.0.1-SNAPSHOT.jar
在开发环境和生产环境之间切换 - 用到的几个注解
@Component
@ConfigurationProperties(prefix = "limit")
@Autowired
@Value("${minMoney}")
Controller如下:
package com.zyl.luckymoney.controller;
import com.zyl.luckymoney.beans.LimitConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.math.BigDecimal;
@RestController
public class HelloController {
// @Value("${minMoney}")
// private BigDecimal minMoney;
//
// @Value("${description}")
// private String description;
// @GetMapping("/hello")
// public String sayHello(){
// return "hello world!";
// }
@Autowired
private LimitConfiguration limitConfiguration;
@GetMapping("/luckymoney")
public String submitluckymoney(){
return ",说明:" + limitConfiguration.getDescription();
}
}