基础3-读取项目的properties配置文件
@PropertySource
@PropertySource注解用来加载指定的配置文件;
@ConfigurationProperties注解是从application.yml来读取的,这是Spring Boot系统级别的配置文件,因此,需要通过@PropertySource注解来加载自定义的属性文件;
person.name=张三 |
package com.springboot.bean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; import java.util.Map; /** * 2020 - 08 - 05 * 9:15 * @ConfigurationProperties * 只有Spring容器中的组件,才能使用该注解,因此,该注解必须注入到Spring容器中,否则会提示错误 * 该注解就是告诉Spring Boot,当前类的属性值与properties/yml文件中的属性值进行绑定 * prefix:可以理解为整个属性树的根节点,解析该根节点下所有的属性,来与java类的属性进行映射,这里是person * */ @Component @ConfigurationProperties(prefix = "person") @PropertySource(value = {"classpath:person.properties"}) public class Person { private String name; private String address; private int age; private String telphone; private Date birthday; private boolean isSingle; private Map<String,Object> map; private List<Object> list; private Car car; @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", address='" + address + '\'' + ", age=" + age + ", telphone='" + telphone + '\'' + ", birthday=" + birthday + ", isSingle=" + isSingle + ", map=" + map + ", list=" + list + ", car=" + car + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getTelphone() { return telphone; } public void setTelphone(String telphone) { this.telphone = telphone; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public boolean isSingle() { return isSingle; } public void setSingle(boolean single) { isSingle = single; } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } public List<Object> getList() { return list; } public void setList(List<Object> list) { this.list = list; } public Car getCar() { return car; } public void setCar(Car car) { this.car = car; } } |
注意:
@PropertySource + @Value(绑定某几个属性)
@PropertySource + @ConfigurationProperties(绑定全部属性)
这2种组合下,才能把person.properties绑定到Person中,如果仅仅是@PropertySource,则无法实现这种效果;
@ImportResource
导入Spring的配置文件,让配置文件里面的内容生效;该注解用在配置类上,用来加载比较常见的配置文件,例如:<beans/>之类的XML配置文件;
@SpringBootApplication @ImportResource(locations = {"classpath:beans.xml"}) public class HelloWordMainApplication { public static void main(String[] args) { SpringApplication.run(HelloWordMainApplication.class, args); } } |
到了Spring Boot这里,官方推荐使用注解的方式,而不再推荐XML方式,因此,某种程度来讲,该注解使用场景不多;