NoSuchBeanDefinitionException: нет подходящего компонента типа "XInterceptor" - PullRequest
0 голосов
/ 06 марта 2020

Я заблудился, убедившись, что все правильно аннотировано. Когда я запускаю сервис, который использует этот новый код, я получаю сообщение об ошибке ниже. Разве перехватчик не является компонентом уже с @Component, и тогда все, что ему нужно, чтобы быть компонентом внутри, является компонентом?

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.demo...XInterceptor' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
    ... 88 common frames omitted

Process finished with exit code 1

У меня есть класс someDecorator, который использует перехватчик, в который я внес изменения:

@Component 
@RequiredArgsConstructor 
public class someDecorator { 

    private final XInterceptor xInterceptor; 
    ...
    private void useTheInterceptor(...) {
      ...
      aList.add(xInterceptor) // and use it for later
    }
}

Теперь xInterceptor, который использует другой класс YProvider

@Component
@RequiredArgsConstructor
public class xInterceptor {

    private final YProvider yProvider;

    public ClientHttpResponse intercept(String str, ...) throws IOException {

        Consumer<String> loggingConsumer = yProvider.getLoggingLevel(str);
        // ... use the consumer 
    }

* * * * * * * * * * * * * * * * * * * * * * * * * * * * там, где это интересно, у него есть два значения. ZProperties, который является классом конфигурации и картой потребителя.

@RequiredArgsConstructor
public class YProvider {

    private final ZProperties zProperties;
    private final Map<String, Consumer<String>> consumers;

    public Consumer<String> getLoggingLevel(String str) {
       // gets a single consumer from zProperties.getExampleMap ...
}

ZProperties просто захватывает карту из файла application.yml:

@Configuration
@ConfigurationProperties(prefix = "some-config")
@EnableConfigurationProperties
@Getter
@Setter
public class ZProperties {
    private Map<String, String> exampleMap;
}

Теперь для заполнения consumers карта в YProvider и для настройки YProvider, у меня есть другой конфиг ConsumerConfig

@Configuration
public class ConsumerConfig {

    @Bean
    public YProvider yProvider(ZProperties zProperties) {
        return new YProvider(zProperties, exmapleMapToConsumerConfiguration());
    }

    public Map<String, Consumer<String>> exmapleMapToConsumerConfiguration() {
        Map<String, Consumer<String>> exmapleMapToConsumerMap = new ConcurrentHashMap<>();
        // add stuff to map

        return exmapleMapToConsumerMap;
    }
}

Ответы [ 2 ]

0 голосов
/ 09 марта 2020

Поскольку у меня были эти файлы в разных пакетах, мне пришлось добавить @ComponentScan с именем пакета, в котором находился Intercepter + Provider, и пакета, в котором находились файлы конфигурации.

0 голосов
/ 06 марта 2020

Возможно, это связано с тем, что вы не указали XInterceptor в качестве компонента в своем файле конфигурации.

Попробуйте добавить это в свой класс ConsumerConfig.

    @Bean
    public XInterceptor getXInterceptor(){
     return new XInterceptor();
    }
...