Springboot2.0加载指定配置文件@PropertySource的使用
1. 在resouces下编写待加载的配置文件
这里使用person.properties
# String
person.last-name=john
# int
person.age=112
# boolean
person.boss=false
# Date
person.birth=2019/11/12
# List<Object>
person.dogs[0].name=jj
person.dogs[0].age=111
person.dogs[1].name=tom
person.dogs[1].age=111
# Map<String, Object>
person.maps.Jack=jackc2
person.maps.Iris=yili8
person.maps.Panda=pandax
person.maps.Adun=gengwang
person.maps.Caedmon=chuankwa
# List
person.lists[0]=1
person.lists[1]=2
person.lists[2]=3
person.lists[3]=4
person.lists[4]=5
2. 在启动类中添加bean类@EnableConfigurationProperties
package cn.jfjb;
import cn.jfjb.bean.Person;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties({Person.class})
public class SbHelloworld01QuickApplication {
public static void main(String[] args) {
SpringApplication.run(SbHelloworld01QuickApplication.class, args);
}
}
3. 在bean中使用@PropertySource加载
package cn.jfjb.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @author john
* @date 2019/11/22 - 8:56
*/
@Component
@PropertySource("classpath:person.properties")
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private boolean boss;
private Date birth;
private List<Dog> dogs;
private Map<String, Object> maps;
private List<Object> lists;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public boolean isBoss() {
return boss;
}
public void setBoss(boolean boss) {
this.boss = boss;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public List<Dog> getDogs() {
return dogs;
}
public void setDogs(List<Dog> dogs) {
this.dogs = dogs;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getLists() {
return lists;
}
public void setLists(List<Object> lists) {
this.lists = lists;
}
@Override
public String toString() {
return "Person{" +
"lastName='" + lastName + '\'' +
", age=" + age +
", boss=" + boss +
", birth=" + birth +
", dogs=" + dogs +
", maps=" + maps +
", lists=" + lists +
'}';
}
}