Хотя @Autowired с @Qualifier в тестовом примере Junit показывает контекст приложения Unable load и исключение Illegalstate
Я использую @KafkaListener в своем приложении, поэтому использую
@Configuration
static class ContextConfiguration {
//create the beans
}
Мой класс, использующий @Autowired @Qualifier("someName") для настройки при написании конфигурации тестового класса, который квалифицируется с "someName", не загружается..
так что он бросает ошибку ниже
Вызвано: org.springframework.beans.factory.NoSuchBeanDefinitionException: нет подходящего bean-компонента типа 'org.springframework.web.client.RestTemplate'
available: ожидается как минимум 1 bean-компонент, который квалифицируется как кандидат autowire. Аннотации зависимостей: {@org.springframework.beans.factory.annotation.Autowired(required=true), @org.springframework.beans.factory.annotation.Qualifier(value=someName)}
1 ответ
В таком случае основная проблема заключается в том, что @Bean("someName") не загружается в контейнер Spring, поэтому при создании bean-компонента взломайте конфигурацию, которая возвращается в @Bean("someName"), например..
@Configuration
static class ContextConfiguration {
@Bean
@Qualifier("InternalKafkaProducer")
public KafkaTemplate<Object, Object> publishingTemplate(){
return new KafkaTemplate(new DefaultKafkaProducerFactory<>(getKafkaTemplate()));
}
}
@Autowired
private KafkaTemplate<Object, Object> kafkaTemplate;
@Test
public void test(){
//some code
}
private static HashMap<String, Object> getKafkaTemplate() {
//return the properties;
}
}//test class end
Main class
@Autowired
@Qualifier("someName")
private KafkaTemplate<Object, Object>
in configuration class
@Bean(name = "InternalKafkaProducer")
public KafkaTemplate<Object, Object> getKafkaTemplate() {
final Map<String, Object> properties = new HashMap<String, Object>();
properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootStrapServer);
properties.put("security.protocol", securityProtocol);
properties.put("sasl.mechanism", saslMechanism);
properties.put("sasl.jaas.config", saslJaasConfig);
properties.put("sasl.login.callback.handler.class", saslOauthCallbackClass);
properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
final KafkaTemplate<Object, Object> template = new KafkaTemplate<Object, Object>(new DefaultKafkaProducerFactory<>(properties));
template.setProducerListener(new KafkaProducerListener("InternalKafkaProducer", template));
return template;
}