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

时间:2019-03-29 17:44:58

标签: java spring-boot

我正在尝试使用@ConfigurationPropertieskey-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}}中注入mantilUpdateconstructor的解决方法

1 个答案:

答案 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

祝你好运!