场景:
我们将一些系统配置参数放在数据库表中,方便随时更改。为了避免频繁读取数据库,我们仅在项目启动时加载一次参数,将这些参数赋值给静态变量。
常量类:
/**
* @Author: BillYu
* @Description: 常量
* @Date: Created in 下午3:56 2018/4/28.
*/
public final class Constants {
/**
* 销售占比
*/
public static Double SELLER_PERCENT = 0.12D;
}
配置类:
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @Author: BillYu
* @Description:初始化赋值
* @Date: Created in 下午5:20 2019/1/9.
*/
@Component
public class SettingConfig implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
Constants.SELLER_PERCENT=0.20D;
}
}
controller测试:
/**
* @Author: BillYu
* @Description:
* @Date: Created in 下午5:07 2018/8/21.
*/
@RequestMapping("/api/system")
@RestController
@Api(description = ")
public class TestController {
@ApiOperation("testInit")
@GetMapping("/init")
public RtData init(){
return ResponseBuilder.success(Constants.SELLER_PERCENT);
}
}
测试结果输出:
{
"code": 200,
"msg": "请求成功",
"data": 0.2
}
证明此时初始化加载已经生效。