1、在 resources目錄下創建 custom.properties 文件,內容如下:
custom.name=Java
custom.module=thread
2、定義配置類(使用@Value注解注入屬性值):
@Component // 指定配置文件路徑 @PropertySource("classpath:custom.properties") public class CustomConfig { @Value("${custom.name}") private String name; @Value("${custom.module}") private String module; public String getResult() { return "name:" + this.name + ",module:" + this.module; } }
3、定義配置類(使用 get/set 方法):
@Component @ConfigurationProperties(prefix = "custom") @PropertySource("classpath:custom.properties") @Data // 引用 lombok注解 public class CustomConfig { private String name; private String module; public String getResult() { return "name:" + this.name + ",module:" + this.module; } }
以上兩種配置類的定義,使用任一即可。
4、進行單元測試:
/** * 測試 SpringBoot 讀取自定義屬性文件 */ @RunWith(SpringRunner.class) @SpringBootTest public class TestCustomConfig { /** * 注入自定義配置類 */ @Autowired CustomConfig customConfig; @Test public void testCustom() { String result = customConfig.getResult(); System.out.println(result); // 結果:name:Java,module:thread } }