Spring Boot如何配置我的Jackson ObjectMapper?

时间:2017-11-29 19:42:22

标签: spring spring-boot groovy dependency-injection

我正在尝试了解Spring / Spring Boot如何管理我负责维护的应用程序的DI。在该应用程序内部,我看到一个MyAppInjector Groovy文件,如下所示:

@Configuration
class MyAppInjector {
    @Autowired
    void configureJackson(ObjectMapper objectMapper) {
        SimpleModule jacksonModule = new SimpleModule()
                .addDeserializer(AccountDeserializer, new AccountDeserializer())
                .addDeserializer(PhoneNumberDeserializer, new PhoneNumberDeserializer())
                .addDeserializer(AddressDeserializer, new AddressDeserializer())
                .addDeserializer(ContactDeserializer, new ContactDeserializer())
                .addDeserializer(CustomerDeserializer, new CustomerDeserializer())
                .addDeserializer(DeploymentInfoDeserializer, new DeploymentInfoDeserializer())
                .addDeserializer(ServiceAgreementDeserializer, new ServiceAgreementDeserializer())

        objectMapper.registerModule(jacksonModule)
    }
}

但是,我没有在应用源代码中的任何位置调用configureJackson(...)。我假设此方法正在配置Jackson ObjectMapper,由Spring用于将JSON序列化为POJO。

但是,Spring如何知道在此配置ObjectMapper?它是否会查找使用@Configuration注释的任何内容,然后看到它在某处注册了杰克逊ObjectMapper,并将其传递给此configureJackson(...)方法?看起来像魔术......

对于使用@Configuration注释的类中的任何方法,这是真的吗?我可以创建一个方法,如:

@Configuration
class MyAppInjector {
    @Autowired
    Fizz fizz(Buzz buzz) {
      new Fizz(buzz)
    }

    @Autowired
    void configureJackson(ObjectMapper objectMapper) {
        SimpleModule jacksonModule = new SimpleModule()
                .addDeserializer(AccountDeserializer, new AccountDeserializer())
                .addDeserializer(PhoneNumberDeserializer, new PhoneNumberDeserializer())
                .addDeserializer(AddressDeserializer, new AddressDeserializer())
                .addDeserializer(ContactDeserializer, new ContactDeserializer())
                .addDeserializer(CustomerDeserializer, new CustomerDeserializer())
                .addDeserializer(DeploymentInfoDeserializer, new DeploymentInfoDeserializer())
                .addDeserializer(ServiceAgreementDeserializer, new ServiceAgreementDeserializer())

        objectMapper.registerModule(jacksonModule)
    }
}

...并期望Spring在构建时智能地查找Buzz实例进入Fizz

1 个答案:

答案 0 :(得分:1)

SpringBoot自己实例化ObjectMapper,因为Spring将Java对象转换为JSON,反之亦然。因此,如果它在类路径中找到Spring引导,它将加载objectMapper。现在在您的configureJackson方法中,您已经引用了ObjectMapper和@Autowired注释,因此Spring将为此方法提供ObjectMapper的实例。

@Autowired注释正在做你所指的魔术。 @Autowired

Fizz fizz(Buzz buzz) {
  new Fizz(buzz)
} 

在这个例子中,Apring将在fizz方法中注入Buzz实例。