Skip to content

Spring Boot 用户自定义配置 #58

Open
@Shellbye

Description

@Shellbye

很多时候我们的代码中是有一些可变\但是又不是经常变的常量的,比如用户等待某个消息的最长等待时间,我们先期暂定30秒,但是后来发现时间有点久,想要改成10秒,那么这个时候其实是有很多解决方案的,比如我们可以把这个写到数据库里,每次都去读取数据库,这个还能做到修改实时生效,但是这样也有一个问题就是太浪费资源,而且我们的可能改一下之后就不再改了,那么每次都读取数据库其实性能也有问题,直接改代码也是一种方案,写成一个常量,以后每次修改都改动代码,这样做的弊端就是每次修改都涉及到上线啥的,其实也比较麻烦。

这个时候一个比较合理的解决方案是使用Spring Boot支持的用户自定义配置,在保证了性能的同时,对其进行修改也是成本比较小的。下面是一个具体的示例。

配置文件 application.properties

custom.waitTime=30

接收Bean

package com.example.demo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@Component
@ConfigurationProperties("custom") // 需要注意这里,得和 application.properties 对应
public class AppProp {

    private Integer waitTime;

    public Integer getWaitTime() {
        return waitTime;
    }

    public void setWaitTime(Integer waitTime) {
        this.waitTime = waitTime;
    }
}

使用

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Main {

    private AppProp appProp;

    @Autowired
    public Main(AppProp appProp) {
        this.appProp = appProp;
    }

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String getSpecial() {
        return String.format("{\"value\": %s}", appProp.getWaitTime());
    }
}

然后启动项目访问 http://localhost:8080/ 就可以看到

{
    key: 30
}

然后当后期需要修改时,只需要修改application.properties即可。

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions