gpt4 book ai didi

java - 如何在构造函数中访问 application.properties 值

转载 作者:行者123 更新时间:2023-12-02 10:04:18 25 4
gpt4 key购买 nike

我正在尝试使用@ConfigurationPropertiesapplication.properties文件加载键值对。

应用程序属性

soap.action.segalRead=Segal/SegalRead
soap.action.mantilUpdate=Mantil/MantilUpdate

SoapUri.java

@ConfigurationProperties(prefix = "soap.action")
public class SoapUri {

@NotNull
private String segalRead;
@NotNull
private String mantilUpdate;

//getters and setters
}

SoapUriTests.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class SoapUriTests {

@Autowired
private SoapUri soapUri;

@Test
public void testSoapUri_returnsSoapAction() {
assertThat(soapUri.getSegalRead()).isEqualTo("Segal/SegalRead");
assertThat(soapUri.getMantilUpdate()).isEqualTo("Mantil/MantilUpdate");
}
}

上述单元测试效果很好。

但是,我需要在实际代码中使用 SoapUri 。考虑以下代码:

public class MantilUpdateReadVO extends RequestClientVO {

@Autowired
private SoapUri soapUri;

public MantilUpdateReadVO(final MantilUpdate mantilUpdate) {
super(mantilUpdate, soapUri.getMantilUpdate(), MantilUpdateResponse.class);
}
}
public class RequestClientVO {

private Object readRequest;
private String serviceName;
private Class<?> unmarshalTargetclass;

public MwsRequestClientVO(Object readRequest, String serviceName, Class<?> unmarshalTargetclass) {
super();
this.readRequest = readRequest;
this.serviceName = serviceName;
this.unmarshalTargetclass = unmarshalTargetclass;
}
//getters and setters
}

上面提示:“在显式调用构造函数时无法引用实例字段soapUri

有谁知道在 super()constructor 中注入(inject) segalReadmantilUpdate 的解决方法

最佳答案

您正在使用字段注入(inject),这不是一个好主意。请参阅 Oliver Gierke 的 Why Field Injection is Evil了解详情。

该字段要在实例构造完成后才能注入(inject);因此,您不能在构造过程中使用注入(inject)字段。

像这样更改代码:

    @Autowired
public MantilUpdateReadVO(final SoapUri soapUri, final MantilUpdate mantilUpdate) {
super(mantilUpdate, soapUri.getMantilUpdate(), MantilUpdateResponse.class);
}

您还需要确保 MantilUpdateReadVO 是一个 Spring Bean;可能需要添加@Component

祝你好运!

关于java - 如何在构造函数中访问 application.properties 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55422960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com