SpringBoot之加載自定義配置文件


SpringBoot默認加載配置文件名為:application.properties和application.yml,如果需要使用自定義的配置文件,則通過@PropertySource注解指定。

 

JavaBean:

package org.springboot.model;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


@Component
@ConfigurationProperties(prefix = "pet")
@Data
// 自定義配置文件路徑
@PropertySource(value = {"classpath:config/pet.properties"})
public class Pet {
    private String name;
    private String type;
}

 

pet.properties(./resources/config/pet.properties)

pet.name=haha
pet.type=dog

 

測試代碼:

package org.springboot;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springboot.model.Pet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {
    @Autowired
    Pet pet;

    // 指定其他配置文件
    @Test
    public void testPet() {
        System.out.println(pet);
    }

}

 

執行結果:

Pet(name=haha, type=dog)

 


免責聲明!

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



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