SpringBoot03全局配置文件与指定配置文件

springboot全局配置文件

@ConfigurationProperties

上一章节已经介绍了用法这里就不再赘述了
详情见:
yaml全局配置文件
为了更好的书写,我们使用properties文件作为配置文件
相关的改动:

person.lastname=张三
person.age=18
person.birth=2017/12/12
person.maps.k1=v1
person.maps.k2=12
person.lists=a,b,b
person.dog.name=dog
person.dog.age=13

其他代码均未改动

注意配置文件为application.properties

运行结果如下:
Person{lastname=‘张三’, age=18, boss=false, birth=Tue Dec 12 00:00:00 CST 2017, maps={k1=v1, k2=12}, lists=[a, b, b], dog=Dog{name=‘dog’, age=13}}

指定配置文件

@PropertySource(value = “classpath:person.properties”)

注意:

要配合@ConfigurationProperties(prefix = “person”)一起使用
同时注销掉全局配置application.properties中的内容

对应的代码修改

1.创建person.properties配置文件

person.lastname=lisi
person.age=18
person.birth=2017/12/12
person.maps.k1=v1
person.maps.k2=12
person.lists=a,b,b
person.dog.name=dog
person.dog.age=13

2.修改person对象的注入方式:

@PropertySource(value = "classpath:person.properties")//与下面的configurationproperties配合使用,
// 具体使用的化要注释掉application里面的参数//value值是路径值
@Component//将对象放入到容器中
@ConfigurationProperties(prefix = "person")//容器中的方法,默认从全局配置中
public class Person {
    private String lastname;
    private int age;
    private boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;

    @Override
    public String toString() {
        return "Person{" +
                "lastname='" + lastname + '\'' +
                ", age=" + age +
                ", boss=" + boss +
                ", birth=" + birth +
                ", maps=" + maps +
                ", lists=" + lists +
                ", dog=" + dog +
                '}';
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int 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 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;
    }

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }
}

运行测试方法得到的结果:
Person{lastname=‘lisi’, age=18, boss=false, birth=Tue Dec 12 00:00:00 CST 2017, maps={k2=12, k1=v1}, lists=[a, b, b], dog=Dog{name=‘dog’, age=13}}

猜你喜欢

转载自blog.csdn.net/tangshuai96/article/details/104396692