(一)创建Spring Boot Web项目ConfigDemo01
- 添加项目依赖
- 设置项目名称与保存位置
- 完成项目初始化工作
(二)创建自定义配置文件
- 说明:如果在配置文件里使用user.name,通过配置文件获取的值可能是操作系统中的用户名,因为操作系统中也是有user.name属性的。
(三)创建自定义配置类
package net.hzy.lesson04.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component // 交给Spring容器管理
@PropertySource("classpath:myconfig.properties") // 加载自定义配置文件
@ConfigurationProperties(prefix="student") // 配置属性,设置前缀
public class StudentConfig {
private String id;
private String name;
private int age;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "StudentConfig{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
(四)编写测试方法
package net.hw.lesson04;
import net.hw.lesson04.config.StudentConfig;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ConfigDemo01ApplicationTests {
@Autowired // 自动装配学生配置实体
private StudentConfig studentConfig;
@Test
void contextLoads() {
}
@Test
public void testStudentConfig() {
// 输出学生配置实体信息
System.out.println(studentConfig);
}
}