Java Quarkus 如何将 @ConfigProperty 传递给构造函数?

san*_*254 3 java inject cdi quarkus

我有以下课程:

@ApplicationScoped
public class AppScopeTest {

    @ConfigProperty(name = "my-config-prop")
    String test;
    
    private TestClass testclass;

    @Inject
    public AppScopeTest () {
        this.testClass= new TestClass (test);
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一些类需要TestClass在创建该类后创建一个新实例。示例如上所示。但如果我这样做,类中的字符串 Test 始终为 null TestClass

所以我的问题是如何读取配置属性并创建一个TestClass以该配置属性作为参数的新实例?

我不希望这是一个方法调用,因为AppScopeTest创建时我想要一个实例TestClass

小智 7

这样做怎么样:

@ApplicationScoped
public class AppScopeTest {

    private final String test;
    
    private TestClass testclass;

    @Inject
    public AppScopeTest (@ConfigProperty(name = "my-config-prop") String test) {
        this.testClass = new TestClass(test);
    }
}
Run Code Online (Sandbox Code Playgroud)