我正在尝试使用@ConfigurationProperties
从key-value
文件中加载application.properties
对。
application.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 ”
有人知道在segalRead
的{{1}}中注入mantilUpdate
和constructor
的解决方法
答案 0 :(得分:1)
您正在使用场注入,这不是一个好主意。有关详细信息,请参见Oliver Gierke的Why Field Injection is Evil。
在构造实例之后才能注入该字段;因此,在构造过程中不能使用注入的字段。
像这样更改代码:
@Autowired
public MantilUpdateReadVO(final SoapUri soapUri, final MantilUpdate mantilUpdate) {
super(mantilUpdate, soapUri.getMantilUpdate(), MantilUpdateResponse.class);
}
您还需要确保MantilUpdateReadVO
是Spring Bean;可能需要添加@Component
。
祝你好运!