SpringBoot 讀取自定義屬性文件


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
        
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM