จะใช้ @ConstructorBinding และ @PropertySource ร่วมกับ @ConfigurationProperties ใน Spring Boot 2.2.4 ได้อย่างไร

ฉันยังใหม่กับ Spring Boot ขณะนี้ ฉันกำลังพยายามสร้างคลาส POJO (SystemProperties.class) เพื่ออ่านค่าในไฟล์คุณสมบัติ (parameter.properties แยกจาก application.properties แต่ยังอยู่ภายใต้ ไดเรกทอรีเดียวกัน /src/main/resources ปัญหาเกิดขึ้นเมื่อฉันใช้ @ConstructorBinding ในคลาสเพื่อที่จะไม่เปลี่ยนรูป

  • @ConstructorBinding จำเป็นต้องใช้กับ @EnableConfigurationProperties หรือ @ConfigurationPropertiesScan
  • @ConfigurationPropertiesScan จะเพิกเฉยต่อคำอธิบายประกอบ @Configuration ซึ่งจำเป็นเมื่อใช้ @PropertySource เพื่อระบุไฟล์
    *.properties ภายนอก

A) SystemProperties.class

@Configuration
@PropertySource("classpath:parameter.properties")

@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {

    private final String test;

    public SystemProperties (
            String test) {
        this.test = test;
    }

    public String getTest() {
        return test;
    }

B) parameter.properties

abc.test=text1

ฉันได้ลองลบคำอธิบายประกอบ @PropertySource แล้ว แต่ไม่สามารถดึงค่าออกมาได้ เว้นแต่ว่ามาจาก application.properties ความช่วยเหลือใด ๆ ที่ชื่นชมอย่างมาก!


person Richard67    schedule 25.02.2020    source แหล่งที่มา


คำตอบ (1)


วิธีแก้ไขปัญหานี้คือการแบ่งชั้นเรียนออกเป็นสองชั้นเรียนโดยมีข้อกังวลสองข้อที่แตกต่างกัน ด้วยโซลูชันดังกล่าว คุณจะรักษาคลาส SystemProperties ที่คุณสร้างขึ้นและเพิ่มคลาสอื่นเพิ่มเติมเพียงเพื่อโหลดพารามิเตอร์ไฟล์คุณสมบัติเพื่อให้สามารถใช้งานได้กับแอปพลิเคชันของคุณ

วิธีแก้ปัญหาจะเป็นดังนี้:

@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {

    private final String test;

    public SystemProperties(
            String test) {
        this.test = test;
    }

    public String getTest() {
        return test;
    }
}

โปรดสังเกตว่าฉันได้ละเว้นคำอธิบายประกอบ @Configuration และ @PropertySource

@Configuration
@PropertySource("classpath:parameter.properties")
public class PropertySourceLoader {
}

โปรดสังเกตว่าฉันได้เพิ่มคำอธิบายประกอบนี้ในคลาสใหม่ที่สร้างขึ้นเพื่อโหลดไฟล์คุณสมบัติเท่านั้น

สุดท้ายนี้ คุณสามารถเพิ่ม @ConfigurationPropertiesScan ในคลาสแอปพลิเคชันหลักของคุณเพื่อเปิดใช้งานกลไกการแมปคุณสมบัติ

person Yonatan Wilkof    schedule 25.02.2020
comment
คำตอบที่ดี มันช่วยฉันได้ในกรณีที่แตกต่างออกไปเล็กน้อยแต่คล้ายกัน บทความนี้อาจมีประโยชน์เช่นกัน: baeldung.com/spring-enable-config-properties - person luke; 31.12.2020