java后端开发第三篇:springboot中资源属性配置及使用

简单记录Springboot中@Configuration,@ConfigurationProperties等与资源属性配置相关的注解使用:

  1. pom.xml中添加依赖
 >
            >org.springframework.boot>
            >spring-boot-configuration-processor>
            >true>
        >

2.项目resources目录下创建属性文件,比如Building.properties:

build.buildName=麒麟D座
build.buildHeight=80.8(备注:并非真实数据,仅仅随意写的测试数据)
build.buildAddress=重庆市黄山大道中段杨柳路

3.创建与属性文件同名的实体类:

Component
@Configuration //定义配置类
@ConfigurationProperties(prefix = "build")//指定在配置文件中的前缀
@PropertySource(value = "classpath:Building.properties")//对应配置文件
public class Building {
    private String buildName;//建筑物名称
    private Double buildHeight;//建筑物高度
    private String buildAddress;//建筑物地址

    public String getBuildName() {
        return buildName;
    }

    public void setBuildName(String buildName) {
        this.buildName = buildName;
    }

    public Double getBuildHeight() {
        return buildHeight;
    }

    public void setBuildHeight(Double buildHeight) {
        this.buildHeight = buildHeight;
    }

    public String getBuildAddress() {
        return buildAddress;
    }

    public void setBuildAddress(String buildAddress) {
        this.buildAddress = buildAddress;
    }

    @Override
    public String toString() {
        return "Building{" +
                "buildName='" + buildName + '\'' +
                ", buildHeight=" + buildHeight +
                ", buildAddress='" + buildAddress + '\'' +
                '}';
    }
}

4.编写controller类:

@RestController
public class BuildController {
    @Autowired
    private Building building;

    @GetMapping(value = "/build")
    public String getBuild() {
        return building.toString();
    }

}

5.测试,在浏览器中访问http://localhost:8080/build,获取到的结果如下:
java后端开发第三篇:springboot中资源属性配置及使用_第1张图片
在浏览器中显示了我们在配置文件中的内容。

你可能感兴趣的:(JVAVA点滴)