二、SpringBoot之yml配置文件

1、给项目设置端口号,及访问路径

server:
  port: 8088
  servlet-path: /study-springboot-hello

2、浏览器相应

3、在yml文件中传入对象,map,list等

server:
  port: 8088
  servlet-path: /study-springboot-hello
person:
  name: 张三
  age: 18
  birth: 2010/01/03
  map: {a1: q,a2: w}
  lists:
    - 李四
    - 王五
  dog:
    name: 小狗
    age: 1

4、写Bean,@ConfigurationProperties(prefix = "person")读取配置信息,以person开头。

    @Component加入到组件中。

Person:

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Date birth;

    private Map<String,Object> map;
    private List<Object> lists;
    private Dog dog;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Map<String, Object> getMap() {
        return map;
    }

    public void setMap(Map<String, Object> map) {
        this.map = map;
    }

    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;
    }
}

 

Dog:

public class Dog {
    private String name;
    private Integer age;

    @Override
    public String toString() {
        return "Dog{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

5、写 SpringBoot测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class HelloWorldMainApplicationTest {

   @Autowired
   Person person;
   @Test
   public void contextLoads() {
      System.out.println(person);
   }

}

注意:测试类包名应与springboot启动类包名一致

6、测试

控制台输出配置文件信息。

完成测试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值