springBoot入门之进行自定义配置

1.配置文件
application.properties配置文件

package com.example.learn;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/*
演示读取配置的Controller
 */
@RestController
public class PropertiesController {
    @Value("${grade}")//绑定配置文件中的变量
    Integer grade;
    @Value("${classnum}")
    Integer classnum;
    @GetMapping("/gradeclass")
    public String gradeClass(){
        return "年纪:"+grade+",班级:"+classnum;
    }
}

测试是否绑定成功

效果图:无需传参,获取配置文件中的数据
1.png

未避免变量名重复,变量最好加前缀school.
2.png

2.利用对象方式
新建一个配置类 SchoolConfig

package com.example.learn;

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

/*
School配置类
 */
@Component
@ConfigurationProperties(prefix = "school")//配置前缀
public class SchoolConfig {
    Integer grade;
    Integer classnum;
//生成get和set方法
    public Integer getGrade() {
        return grade;
    }
    public Integer getClassnum() {
        return classnum;
    }
    public void setGrade(Integer grade) {
        this.grade = grade;
    }
    public void setClassnum(Integer classnum) {
        this.classnum = classnum;
    }
}

新建一个类 ConfigController

package com.example.learn;

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

/*
读取配置类
 */
@RestController
public class ConfigController {
@Autowired
SchoolConfig schoolConfig;
@GetMapping("/gradeconfig")
public String gradeclass(){
    return "年纪:"+schoolConfig.grade+",班级:"+schoolConfig.classnum;
}
}

标签: SpringBoot

添加新评论