先创建一个Person对象,如下
package com.yimin.helloworld.bean;
import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Component
@ConfigurationProperties(prefix = "person")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
private String name;
private int age;
private List<String> friends;
}
使用
@ConfigurationProperties(prefix = "person")从配置文件中读取内容与属性进行匹配,prefix表示以...开头必须是容器中的组件才能对属性赋值:
@Component相当于是bean标签
@ConfigurationProperties相当于是bean标签内的属性注入
配置文件application.yaml内容如下
person:
name: "zhangsan"
age: 18
friends:
- "lisi"
- "wangwu"
使用spring的测试类进行测试
package com.yimin.helloworld;
import com.yimin.helloworld.bean.Person;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class HelloworldApplicationTests {
/**
* 自动注入
*/
@Autowired
Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
@Autowired:使用前面的bean自动为当前对象的属性赋值
运行结果
Person(name=zhangsan, age=18, friends=[lisi, wangwu])
这样就实现从配置文件中为对象属性赋值
application.properties内容如下,将yaml中的内容注释,测试结果相同
# 设置对象属性的值
person.name=zhangsan
person.age=18
person.friends=lisi,wangwu
也可以在属性上使用spring的@Value注解为对象属性赋值,值可以从配置文件中取(使用${}), 以properties配置文件为例,如
package com.yimin.helloworld.bean;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Component
// @ConfigurationProperties(prefix = "person")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Person {
@Value("zhangsan")
private String name;
@Value("${person.age}")
private int age;
private List<String> friends;
}
这里没有对friends属性赋值,结果应为null
Person(name=zhangsan, age=18, friends=null)
注意@Value不支持数据校验,不支持Map等较复杂的类型
本文章使用limfx的vscode插件快速发布