使用@PropertySource加载自定义配置文件
1、创建Spring Boot Web项目ConfigDemo01
设置项目元数据
添加项目依赖
设置项目名称与保存位置
完成项目初始化工作
2、创建自定义配置文件
在resources下创建myconfig.properties文件
3、创建自定义配置类
在net.gzm.lesson04包里创建配置类StudentConfig
package net.gzm.lesson04;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component //让Spring容器来管理Bean
@PropertySource("classpath:myconfig.properties") //加载自定义配置文件
@ConfigurationProperties(prefix = "student") // 此注解必须要Component注解
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 +
'}';
}
}
4、编写测试方法
点开测试类ConfigDemo01ApplicationTests
编写测试方法
注入学生配置实体
输出学生配置实体信息
4、运行测试方法
5、修改测试方法代码
说明:注入的StudentConfig名称不必是studentConfig,在Spring Boot 2.3.2里,StudentConfig的注解@Component默认是单例的,因此不会因为注入名称是studentConfig1而产生的两个StudentConfig实例。
6、再次运行测试方法
- 可以看到,StudentConfig注入名称改成studentConfig1之后,测试结果依然相同,不受注入名称变化的任何影响。
课堂练习:在Web页面显示学生配置信息
创建控制器StudentController
运行查看效果
访问http://localhost:8080/student查看效果
使用@ImportResource加载XML配置文件
1、创建创建Spring Boot Web项目ConfigDemo02
设置项目元数据
添加配置文件
设置名称与保存位置
完成项目初始化工作
2、创建Bean - 自定义服务类
在net.gzm.lesson04包里创建CustomService子包再创建CustomService类
3、创建自定义JavaBean配置文件
在resources目录里创建配置文件beans.xml
在元素里添加子元素,定义自定义服务类的JavaBean
定义一个Bean,指定Bean的名称及类所在的路径
4、在启动类上添加注解,加载自定义JavaBean配置文件
在启动类上添加注解@ImportResource(“classpath:beans.xml”)
在Spring Boot启动后,Spring容器中就会自动实例化一个名为customService的JavaBean
5、打开测试类,编写测试方法
点开测试类ConfigDemo02ApplicationTests
注入在JavaBean配置文件里定义的Bean,然后调用其方法
运行测试方法,查看结果
四、使用@Configuration编写自定义配置类
使用@Configuration编写自定义配置类,这是Spring Bboot的推荐方式
1、创建Spring Boot Web项目ConfigDemo03
设置项目元数据
2、创建Bean - 自定义服务类
在net.gzm.lesson04包里创建CustomService类
3、创建自定义配置类MyConfig
在net.gzm.lesson04包里创建自定义配置类CustomConfig
添加注解@Configuration,指定配置类
创建获取Bean的方法getCustomService()
4、打开测试类,编写测试方法
点开测试类ConfigDemo03ApplicationTests
运行测试方法contextLoads(),查看结果