一、使用@PropertyResource记载配置文件
1、在resource目录下新建一个testMyproperty.properties配置文件
#对实体类对象Myporperty进行属性设置
test.id=1
test.name=Jerry
2、在src/main/com/chen/domain下自定义一个配置类MyProperty
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Configuration //表明当前类是一个自定义配置类
//@Component // 可以替换@Configuration和@EnableConfigurationProperties(MyProperty.class)这两个注解
@PropertySource("classpath:testMyproperty.properties")// 指定自定义配置文件的路径和名称
@EnableConfigurationProperties(MyProperty.class)//表明开启当前配置类的属性注入功能
@ConfigurationProperties(prefix = "test")// 批量注入,将testMyproperty.properties前缀为test的属性值注入到当前配置类的属性中
public class MyProperty {
private Integer id;
private String name;
// 省略setter方法和getter方法
// 省略toString方法
}
3、编写测试类
import com.chen.domain.MyProperty;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory

本文介绍了SpringBoot中三种自定义配置的方式:1) 使用@PropertyResource加载properties配置文件;2) 使用@ImportResource加载XML配置文件,适用于特殊情况;3) 使用@Configuration创建配置类。详细步骤包括配置文件创建、配置类编写和测试,展示了如何将Bean注入Spring容器。
最低0.47元/天 解锁文章
1238

被折叠的 条评论
为什么被折叠?



