美文网首页
springboot 基于properties文件类型安全配置

springboot 基于properties文件类型安全配置

作者: 喊我小王吧 | 来源:发表于2018-12-23 21:44 被阅读0次

常规配置都得采用@value进行属性配置,属性值比较少的情况下还可以接受,但是属性值多的情况下就比较麻烦了。

springboot 为我们提供了一种比较简单的注入方法!

基于properties文件类型安全配置,代码如下

第一种方法

直接在application.properties文件中配置

w.name = wang
w.sex  = boy 

Student

@Component
@ConfigurationProperties(prefix = "w")
public class Student {

    String name;
    String sex;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

controller

    @Autowired
    private Student student;

    //类型安全的配置
    @RequestMapping("student")
    @ResponseBody
    public Student getUser1() {
        return student;
    }

结果

{"name":"wl","sex":"boy"}

另一种方法

** 可以自定义properties文件 **

a.properties

w.name = wang
w.sex  = boy 

这次不在application文件里面配置,我们在外面新建的配置文件。

所以这次我们必须在Student上指定一下文件的路径

@PropertySource(value = "classpath:a.properties")

我们在来测试:

{"name":"wl","sex":"boy"}

相关文章

网友评论

      本文标题:springboot 基于properties文件类型安全配置

      本文链接:https://www.haomeiwen.com/subject/ptjokqtx.html