Spring Boot讀取自定義外部屬性

隱身的提莫發表於2021-05-25

測試的環境:Spring Boot2 + Maven +lombok

準備需要用到的基礎類:

public class People {
    private String name;
    private String address;
    private String phone;
}

準備預設的配置檔案application.properties,內容如下

people.default.name=zs
people.default.address=ccc
people.default.phone=122122

準備自定義配置檔案people.properties,內容如下

people.default.name=test-zs
people.default.address=test-address
people.default.phone=111111

準備測試類

@RestController
public class PeopleController {

    @Autowired
    private People people;

    @RequestMapping("/test1")
    public void test1(){
        System.out.println(people);
    }
}

第一種情況:讀取預設配置檔案中的自定義屬性(如application.properties)

1、直接在指定類讀取檔案屬性

@Data
//@Setter
@ToString
@Configuration
@ConfigurationProperties(prefix = "people.default")
public class People {
    private String name;
    private String address;
    private String phone;
}

測試結果:

注意:類用到了lombok的註解(@Data)或者使用@Setter註解。所以有getter/setter。如果沒有使用註解,則需要setter方法才能讀取成功。

2、配合@Vaule讀取檔案屬性

@Configuration
public class PeopleConfigrution {

    @Value("${people.default.name}")
    private String name;
    @Value("${people.default.address}")
    private String address;
    @Value("${people.default.phone}")
    private String phone;

    @Bean
    public People initPeople(){
        People people=new People();
        people.setName(name);
        people.setPhone(phone);
        people.setAddress(address);
        return people;
    }
}

測試結果:

3、使用Environment讀取

@Configuration
public class PeopleConfigrution {

    @Autowired
    private Environment environment;

    @Bean
    public People initPeople(){
        People people=new People();
        people.setName(environment.getProperty("people.default.name"));
        people.setPhone(environment.getProperty("people.default.phone"));
        people.setAddress(environment.getProperty("people.default.address"));
        return people;
    }
}

測試結果:

第二種情況:讀取自定義檔案中的屬性(如people.properties)

需指定讀取檔案的位置,可使用@PropertySource註解指定,如

@Data
//@Setter
@ToString
@Configuration
@PropertySource("classpath:people.properties")  //指定讀取檔案位置,可與讀取預設檔案第一種方式相比。
@ConfigurationProperties(prefix = "people.default")
public class People {
    private String name;
    private String address;
    private String phone;
}

測試結果:

以上列舉的不是全部方式,載入檔案的方式還有其他方式,這篇只是列舉常用的方式。

相關文章