Модуль Джексона не зарегистрирован после обновления до Spring Boot 2 - PullRequest
6 голосов
/ 07 мая 2020

Я обновляюсь с Spring Boot 1.5.21 до 2.2.5.

Мне нужно использовать MonetaryModule для десериализации вызовов rest и в зависимости от Spring ObjectMapper.

Я определил такой bean-компонент для этого модуля в некотором классе @Configuration (MonetaryModule расширяет Module):

@Bean
public MonetaryModule monetaryModule() {
    return new MonetaryModule();
}

Я вижу, что в конечной точке /beans он был создан. Однако на самом деле он не загружается в ObjectMapper. После долгой отладки и изучения кода Spring я пришел к выводу, что в JacksonAutoConfiguration что-то не так. у него есть внутренний класс c, называемый JacksonObjectMapperBuilderConfiguration, и в нем есть bean, который создает Jackson2ObjectMapperBuilder. в процессе создания есть вызов customize(), который в конечном итоге переходит к этому коду:

private void configureModules(Jackson2ObjectMapperBuilder builder) {
    Collection<Module> moduleBeans = getBeans(this.applicationContext, Module.class);
    builder.modulesToInstall(moduleBeans.toArray(new Module[0]));
}

Кажется, этот код отвечает за загрузку модулей в ObjectMapper. Проблема в том, что этот Jackson2ObjectMapperBuilder не фактически создан. Он появляется в конечной точке /beans, но де-факто, когда я нахожусь там, я не попадаю в точку останова. Это объясняет, почему модуль не загружается в ObjectMapper.

Вопрос, почему этот код не вызывается? и почему /bean указывает на то, что bean-компонент существует?

Edit - Добавление отчета об оценке условий:

============================
CONDITIONS EVALUATION REPORT
============================


Positive matches:
-----------------

   AopAutoConfiguration matched:
      - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)

   AopAutoConfiguration.AspectJAutoProxyingConfiguration matched:
      - @ConditionalOnClass found required class 'org.aspectj.weaver.Advice' (OnClassCondition)

   AopAutoConfiguration.AspectJAutoProxyingConfiguration.CglibAutoProxyConfiguration matched:
      - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition)

   ConfigServiceBootstrapConfiguration#configServicePropertySource matched:
      - @ConditionalOnProperty (spring.cloud.config.enabled) matched (OnPropertyCondition)
      - @ConditionalOnMissingBean (types: org.springframework.cloud.config.client.ConfigServicePropertySourceLocator; SearchStrategy: all) did not find any beans (OnBeanCondition)

   ConfigServiceBootstrapConfiguration.RetryConfiguration matched:
      - @ConditionalOnClass found required classes 'org.springframework.retry.annotation.Retryable', 'org.aspectj.lang.annotation.Aspect', 'org.springframework.boot.autoconfigure.aop.AopAutoConfiguration' (OnClassCondition)
      - @ConditionalOnProperty (spring.cloud.config.fail-fast) matched (OnPropertyCondition)

   ConfigServiceBootstrapConfiguration.RetryConfiguration#configServerRetryInterceptor matched:
      - @ConditionalOnMissingBean (names: configServerRetryInterceptor; SearchStrategy: all) did not find any beans (OnBeanCondition)

   ConfigurationPropertiesRebinderAutoConfiguration matched:
      - @ConditionalOnBean (types: org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor; SearchStrategy: all) found bean 'org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor' (OnBeanCondition)

   ConfigurationPropertiesRebinderAutoConfiguration#configurationPropertiesBeans matched:
      - @ConditionalOnMissingBean (types: org.springframework.cloud.context.properties.ConfigurationPropertiesBeans; SearchStrategy: current) did not find any beans (OnBeanCondition)

   ConfigurationPropertiesRebinderAutoConfiguration#configurationPropertiesRebinder matched:
      - @ConditionalOnMissingBean (types: org.springframework.cloud.context.properties.ConfigurationPropertiesRebinder; SearchStrategy: current) did not find any beans (OnBeanCondition)

   EncryptionBootstrapConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.security.crypto.encrypt.TextEncryptor' (OnClassCondition)

   PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer matched:
      - @ConditionalOnMissingBean (types: org.springframework.context.support.PropertySourcesPlaceholderConfigurer; SearchStrategy: current) did not find any beans (OnBeanCondition)


Negative matches:
-----------------

   AopAutoConfiguration.AspectJAutoProxyingConfiguration.JdkDynamicAutoProxyConfiguration:
      Did not match:
         - @ConditionalOnProperty (spring.aop.proxy-target-class=false) did not find property 'proxy-target-class' (OnPropertyCondition)

   AopAutoConfiguration.ClassProxyingConfiguration:
      Did not match:
         - @ConditionalOnMissingClass found unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition)

   DiscoveryClientConfigServiceBootstrapConfiguration:
      Did not match:
         - @ConditionalOnProperty (spring.cloud.config.discovery.enabled) did not find property 'spring.cloud.config.discovery.enabled' (OnPropertyCondition)

   EncryptionBootstrapConfiguration.RsaEncryptionConfiguration:
      Did not match:
         - Keystore nor key found in Environment (EncryptionBootstrapConfiguration.KeyCondition)
      Matched:
         - @ConditionalOnClass found required class 'org.springframework.security.rsa.crypto.RsaSecretEncryptor' (OnClassCondition)

   EncryptionBootstrapConfiguration.VanillaEncryptionConfiguration:
      Did not match:
         - @ConditionalOnMissingClass found unwanted class 'org.springframework.security.rsa.crypto.RsaSecretEncryptor' (OnClassCondition)


Exclusions:
-----------

    None


Unconditional classes:
----------------------

    None

Кроме того, прилагается результат вывода /conditions & /beans конечных точек ( Слишком большой, чтобы вставить в сам пост)

вывод конечных точек

1 Ответ

1 голос
/ 18 мая 2020

Отчет об оценке вашего состояния показывает следующее:

        "JacksonAutoConfiguration.JacksonObjectMapperConfiguration#jacksonObjectMapper": {
          "notMatched": [
            {
              "condition": "OnBeanCondition",
              "message": "@ConditionalOnMissingBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found beans of type 'com.fasterxml.jackson.databind.ObjectMapper' jacksonBuilder"
            }
          ],
          "matched": []
        },

Это означает, что условие автоконфигурации Spring Boot отключается, поскольку ваше приложение уже предоставляет свое мнение по этому вопросу: уже есть ObjectMapper bean-компонент с именем jacksonBuilder; он предоставляется приложением или некоторым классом конфигурации в используемой вами библиотеке.

В этом случае это происходит из класса конфигурации, как указано конечной точкой beans:

        "jacksonBuilder": {
          "aliases": [],
          "scope": "singleton",
          "type": "com.fasterxml.jackson.databind.ObjectMapper",
          "resource": "class path resource [com/behalf/core/authorization_domain/config/AuthorizationDomainConfiguration.class]",
          "dependencies": []
        },

Здесь вы должны связаться с разработчиками этого AuthorizationDomainConfiguration и сообщить им, что они не должны отвергать мнение приложения о JSON (де) сериализации.

...