创建Spring Boot的Web项目PropertiesDemo
利用Spring Initializr方式创建项目
添加依赖
设置项目名称及保存位置
在application.properties里添加相关配置
点开resource目录,查看应用程序属性配置文件
配置tomcat端口号和web虚拟路径
对象类型的配置与使用
(1)创建Pet类
(2)创建Person类
package net.gzm.lesson03;
import java.util.List;
import java.util.Map;
public class Person {
private int id;
private String name; //姓名
private List hobby; //爱好
private Map family; //家庭成员
private Pet pet; //宠物
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List getHobby() {
return hobby;
}
public void setHobby(List hobby) {
this.hobby = hobby;
}
public Map getFamily() {
return family;
}
public void setFamily(Map family) {
this.family = family;
}
public Pet getPet() {
return pet;
}
public void setPet(Pet pet) {
this.pet = pet;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", hobby=" + hobby +
", family=" + family +
", pet=" + pet +
'}';
}
}
(3)在application.properties里配置对象
#配置对象
person.id=1
person.name=张三丰
person.hobby=旅游,美食,音乐
person.family.father=张云光
person.family.mother=吴文燕
person.family.grandpa=张宏宇
person.famliy.grandma=唐雨欣
person.family.son=张君宝
person.family.daughter=张晓敏
person.pet.type=泰迪犬
person.pet.name=瑞瑞
(4)给Person类添加注解
添加注解@Component,交给Spring去管理
添加注解@ConfigurationProperties(prefix = “person”)
(5)给Pet类添加注解
添加注解@Component,交给Spring去管理
添加注解@ConfigurationProperties(prefix = “person.pet”) - 可以不用添加
(6)从Spring容器里获取Person类的实例并输出
实现接口ApplicationContextAware,实现其抽象方法setApplicationContext
声明ApplicationContext对象,并在setApplicationContext里初始化
从Spring容器中获取Person类的实例并输出
运行测试类,查看结果
在测试类里添加测试方法testPet()
运行测试方法testPet(),查看结果
去掉Pet类的配置属性的注解@ConfigurationProperties(prefix = “person.pet”)
运行测试方法testPet(),查看结果
修改application.properties,配置宠物对象
再次运行测试方法testPet(),查看结果
大家可以看到,宠物对象的属性依然没有被注入,下面我们换一种属性注解的方式,采用@Value注解方式。
给Pet类的属性添加值注解@Value
再次运行测试方法testPet(),查看结果
改成普通文件
新建yaml文件
运行测试方法contextLoads(),查看结果
运行测试方法testPet(),查看结果
课后作业
任务:修改StudentInfo项目输出学生信息
创建学生实体类
添加注解@Component
添加注解@ConfigureProperties
将application.properties更名为application.yaml
配置student对象属性
修改控制器StudentInfoController,student()方法里返回student的值
运行启动类
在浏览器里访问http://localhost:8080/student