属性注入
在application.yml添加以下配置
author: name: 莫提 age: 22 isMan: true # 日期格式必须为 yyyy/MM/dd HH:mm:ss birthday: 1999/07/29 12:00:00 # 数组或集合使用,分割 friends: 张三,李四,王五,赵六 # 此处为JSON字符串,双引号包裹 school: "{'name':'宜春学院','location':'江西-宜春','major':'计算机科学与技术'}"
@SpringBootTest public class InjectionTest { /** * 注入基本数据类型 */ @Value("${author.name}") private String name; @Value("${author.age}") private Integer age; @Value("${author.isMan}") private Boolean isMan; /** * 注入日期 */ @Value("${author.birthday}") private Date birthday; /** * 注入数组或集合 */ @Value("${author.friends}") private List<String> friends; /** * 注入JSON转为Map */ @Value("#{${author.school}}") private Map<String,Object> school; @Test public void test(){ System.out.println("name = " + name); System.out.println("age = " + age); System.out.println("birthday = " + birthday); System.out.println("isMan = " + isMan); System.out.println("friends = " + friends); System.out.println("school = " + school); } }
对象注入
使用@ConfigurationProperties(prefix = "前缀")
,比如上文在application.yml
中配置的信息,那么author
就是前缀。注意使用对象注册的时候就不可以在注入JSON了
@Data @Component @ConfigurationProperties(prefix = "author") public class Author { private String name; private Integer age; private Date birthday; private Boolean isMan; private List<String> friends; }
@SpringBootTest public class InjectionTest { /** * 注入对象 */ @Autowired private Author author; @Test public void test(){ System.out.println("author = " + author); } }
自定义配置文件并使用对象注入
在resources
目录下创建custom.properties
配置文件,并填写以下配置
project.name=测试DEMO project.jdk=1.8
使用@PropertySource
注解指定配置文件,然后配合@ConfigurationProperties(prefix = "前缀")
即可完成对象注入
@Data @Component @ConfigurationProperties(prefix = "project") @PropertySource("classpath:/custom.properties") public class Project { private String name; private String jdk; }
@SpringBootTest public class InjectionTest { /** * 注入自定义配置文件对象 */ @Autowired private Project project; @Test public void test(){ System.out.println("project = " + project); } }