一、全局配置文件概述
全局配置文件能够对一些默认配置值进行修改。Spring Boot使用一个application.properties或者application.yaml的文件作为全局配置文件,该文件存放在src/main/resource目录或者类路径的/config,一般会选择resource目录。
二、Application.properties配置文件
(一)创建Spring Boot的Web项目PropertiesDemo
(二)在application.properties里添加相关配置
点开resource目录,查看应用程序属性配置文件
1、配置tomcat端口号和web虚拟路径
#修改tomcat默认端口号
server.port=8888
#修改web虚拟路径
server.servlet.context-path=/lzy
.更多配置属性,详见官网https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
.启动应用,查看控制台
# 2、对象类型的配置与使用
(1)创建Pet类
package net.hw.lesson03.bean;
/**
* 功能:宠物实体类
* 作者:华卫
* 日期:2021年04月28日
*/
public class Pet {
private String type; // 类型
private String name; // 名字
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Pet{" +
"type='" + type + '\'' +
", name='" + name + '\'' +
'}';
}
}
package net.hw.lesson03.bean;
import java.util.List;
import java.util.Map;
public class Person {
private int id; // 编号
private String name; // 姓名
private List<String> hobby; // 爱好;
private Map<String, String> 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<String> getHobby() {
return hobby;
}
public void setHobby(List<String> hobby) {
this.hobby = hobby;
}
public Map<String, String> getFamily() {
return family;
}
public void setFamily(Map<String, String> 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=瑞瑞
···
D:\IdeaProjects\PropertiesDemo>cd src/main/resources
D:\IdeaProjects\PropertiesDemo\src\main\resources>native2ascii -encoding utf8 application.properties
#\u4fee\u6539tomcat\u9ed8\u8ba4\u7aef\u53e3\u53f7
server.port=8888
#\u4fee\u6539web\u865a\u62df\u8def\u5f84
server.servlet.context-path=/lzy
#\u914d\u7f6e\u5bf9\u8c61
person.id=1
person.name=\u5f20\u4e09\u4e30
person.hobby=\u65c5\u6e38,\u7f8e\u98df,\u97f3\u4e50
person.family.father=\u5f20\u4e91\u5149
person.family.mother=\u5434\u6587\u71d5
person.family.grandpa=\u5f20\u5b8f\u5b87
person.famliy.grandma=\u5510\u96e8\u6b23
person.family.son=\u5f20\u541b\u5b9d
person.family.daughter=\u5f20\u6653\u654f
person.pet.type=\u6cf0\u8fea\u72ac
person.pet.name=\u745e\u745e
D:\IdeaProjects\PropertiesDemo\src\main\resources>