我曾经有一个项目,该项目使用RestTemplate处理对提供某些位置坐标的第三方服务的调用,我们将其称为提供者A。
为此,我使用了以下配置:
@Configuration
@EnableConfigurationProperties(MyProjectProperties.class)
public class MyProjectConfiguration {
@Autowired
private MyProjectProperties properties;
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(createClientHttpRequestFactory());
}
private HttpComponentsClientHttpRequestFactory createClientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(
createHttpClient());
int requestTimeout = properties.getLocationServices()
.getHttpRequestTimeout();
factory.setReadTimeout(requestTimeout);
factory.setConnectTimeout(requestTimeout);
return factory;
}
private HttpClient createHttpClient() {
HttpClientBuilder builder = HttpClientBuilder.create();
builder.useSystemProperties();
builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
builder.setMaxConnTotal(
properties.getLocationServices().getMaximumTotalConcurrentHttpConnections());
builder.setMaxConnPerRoute(properties.getLocationServices()
.getMaximumConcurrentHttpConnectionsPerRoute());
return builder.build();
}
}
然后我有一个使用RestTemplate调用外部提供程序的组件:
@Service
@Qualifier("ALocationProviderAdapter")
@Slf4j
public class ALocationProviderAdapter implements LocationAdapter {
private final RestTemplate restTemplate;
private final String urlTemplate;
@Autowired
public ALocationProviderAdapter(
@Value("${aprovider.url}") String urlTemplate, RestTemplate restTemplate) {
this.urlTemplate = urlTemplate;
this.restTemplate = restTemplate;
}
@Override
public List<Location> getLocations(String id, String latitude, String longitude) {
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("Lat", latitude);
uriVariables.put("Lng", longitude);
try {
ResponseEntity<AProviderLocationResponse> response = restTemplate.getForEntity(urlTemplate,
AProviderLocationResponse.class, uriVariables);
if (response.getStatusCode() != HttpStatus.OK || response.getBody() == null || response
.getBody().getLocations().isEmpty()) {
return Collections.emptyList();
}
//Some additional logic to transform the data
} catch (RestClientException e) {
// Exception handling
}
}
但是,现在我们需要集成另一个第三方服务,该服务也提供了不同的位置,我们将其称为提供者B。由于两者的过程非常相似,所以我决定将RestTemplate提取到已定义的类中作为一个组件,因此每次我想收集位置时,都可以调用帮助程序类。
这是我的助手类:
@Component
@Slf4j
public class RestTemplateHelper {
private RestTemplate restTemplate;
@Autowired
public RestTemplateHelper(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public List<Location> fetchLocationsResponseEntity(String orgCode, String url,
Map<String, String> uriVariables, Class<? extends LocationListResponse> clazz) {
List<Location> locations = null;
ResponseEntity<? extends LocationListResponse> response = null;
try {
response = restTemplate.getForEntity(url, clazz, uriVariables);
if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null
&& !CollectionUtils.isEmpty(response.getBody().getLocations())) {
// Some logic to transform the data
} else {
locations = Collections.emptyList();
}
} catch (RestClientException e) {
// Exception handling
} catch (LocationsConversionException e) {
// Exception handling
}
return locations;
}
public RestTemplate getRestTemplate() {
return this.restTemplate;
}
}
现在,我以这种方式从适配器调用RestTemplateHelper:
@Service
@Qualifier("ALocationProviderAdapter")
@Slf4j
public class ALocationProviderAdapter implements LocationAdapter {
private final String serviceUrl;
private final RestTemplateHelper restTemplateHelper;
@Autowired
public ALocationProviderAdapter(@Value("${aprovider.url}") String serviceUrl,
RestTemplateHelper restTemplateHelper) {
this.serviceUrl = serviceUrl;
this.restTemplateHelper = restTemplateHelper;
}
@Override
public List<Location> getLocations(String id, String latitude, String longitude) {
List<Location> locations = null;
Map<String, String> uriVariables = new HashMap<>();
uriVariables.put("Lat", latitude);
uriVariables.put("Lng", longitude);
locations = restTemplateHelper.fetchLocationsResponseEntity(id, serviceUrl,
uriVariables, AProviderListResponse.class);
return locations;
}
尽管如此,当我尝试使用此新的RestTemplateHelper运行JUnit测试时,却得到了以下信息:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.myproj.test.AProviderAdapterTest': Unsatisfied dependency expressed through field 'restTemplateHelper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myproj.utils.RestTemplateHelper.RestTemplateHelper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:584)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:370)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1336)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:393)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.myproj.utils.RestTemplateHelper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1506)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:581)
... 28 common frames omitted
这是单元测试课:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ProjectConfiguration.class)
public class ALocationProviderAdapterTest {
private static final String URL_TEMPLATE = "http://url.template.com";
@Autowired
private RestTemplateHelper restTemplateHelper;
private MockRestServiceServer mockServer;
private ALocationProviderAdapter adapter;
@Before
public void setup() {
mockServer = MockRestServiceServer.createServer(restTemplateHelper.getRestTemplate());
adapter = new ALocationProviderAdapter(URL_TEMPLATE, restTemplateHelper);
}
@Test
public void whenParamsAreOk_shouldReturnFullLocationsList() {
givenRequestWithResponseBody("aprovider/locations.xml");
List<Location> locations = getLocations();
mockServer.verify();
assertThat(locations).isNotNull();
assertThat(locations).hasSize(5);
}
}
我想知道是否应该做一些其他事情才能使用助手类,还是应该在每个服务使用者类中使用必需的Spring RestTemplate?