I have a bean for an webservice client in my project which requires some configuration settings to be injected. We are using Spring 3.1. Currently the best idea that came up was using the @Value annotation like this:
@Service
public class MyWebServiceClient {
private String endpointUrl;
@Required
@Value("${mywebserviceClient.endpointUrl}")
public void setEndpointUrl(String endpointUrl) {
this.endpointUrl = endpointUrl;
}
}
However I don't really like hardcoding the property name into the class. It also has the problem that there is no way to have more than one client with different settings in the same context (as there is only one property and this is hardcoded). Is there a more elegant way of doing this with autowiring or should I resort to plain old xml configuration for doing this?
I would use JavaConfig to do this.
More specifically, I would use JavaConfig to create multiple instances of MyWebServiceClient, and have the config be @Value'd with the proper endpoint property keys.
Something like this:
@Configuration
public class MyWebServiceConfig {
@Required
@Value("${myWebserviceClient1.endpointUrl")
private String webservice1Url;
@Required
@Value("${myWebserviceClient2.endpointUrl")
private String webservice2Url;
@Required
@Value("${myWebserviceClient3.endpointUrl")
private String webservice3Url;
@Bean
public MyWebServiceClient webserviceClient1() {
MyWebServiceClient client = createWebServiceClient();
client.setEndpointUrl(webservice1Url);
return client;
}
@Bean
public MyWebServiceClient webserviceClient2() {
MyWebServiceClient client = createWebServiceClient();
client.setEndpointUrl(webservice2Url);
return client;
}
@Bean
public MyWebServiceClient webserviceClient3() {
MyWebServiceClient client = createWebServiceClient();
client.setEndpointUrl(webservice3Url);
return client;
}
}
With this, you should have 3 instances of MyWebServiceClient in your ApplicationContext available via the names of the methods annotated with @Bean.
Here is some more documentation to JavaConfig for your convenience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With