springboot 基于properties 类型安全配置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_38361347/article/details/85226678

常规配置都得采用@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”}

猜你喜欢

转载自blog.csdn.net/weixin_38361347/article/details/85226678