View Javadoc
1   /*
2    * Copyright (c) 2023 Kaiserpfalz EDV-Service, Roland T. Lichti
3    *
4    * This program is free software; you can redistribute it and/or
5    * modify it under the terms of the GNU Lesser General Public
6    * License as published by the Free Software Foundation; either
7    * version 3 of the License, or (at your option) any later version.
8    *
9    * This program is distributed in the hope that it will be useful,
10   * but WITHOUT ANY WARRANTY; without even the implied warranty of
11   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12   * Lesser General Public License for more details.
13   *
14   * You should have received a copy of the GNU Lesser General Public License
15   * along with this program; if not, write to the Free Software Foundation,
16   * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17   */
18  package de.kaiserpfalzedv.commons.jackson;
19  
20  import org.springframework.beans.factory.annotation.Autowired;
21  import org.springframework.context.ApplicationContext;
22  import org.springframework.context.annotation.Bean;
23  import org.springframework.context.annotation.Configuration;
24  import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
25  import org.springframework.http.converter.json.SpringHandlerInstantiator;
26  
27  import com.fasterxml.jackson.databind.cfg.HandlerInstantiator;
28  
29  import lombok.extern.slf4j.Slf4j;
30  
31  /**
32   * Enables the usage of {@link Autowired} in Json objects.
33   *
34   * @author klenkes74 {@literal <rlichti@kaiserpfalz-edv.de>}
35   * @version 1.0.0
36   * @since 2023-12-08
37   */
38  @Configuration
39  @Slf4j
40  public class JsonAutowiringConfiguration {
41      /** @return the Jackson2ObjectMapperBuilder that enables the {@link Autowired} annotation in Jackson deserialized objects. */
42      @Bean
43      public Jackson2ObjectMapperBuilder objectMapperBuilder(final HandlerInstantiator handlerInstantiator) {
44          final Jackson2ObjectMapperBuilder result = new Jackson2ObjectMapperBuilder();
45          result.handlerInstantiator(handlerInstantiator);
46  
47          log.debug("Created modified Jackson ObjectMapperBuilder. builder={}", result);
48          return result;
49      }
50  
51  
52      /** @return The HandlerInstantiator needed by the {@link #objectMapperBuilder(HandlerInstantiator)} */
53      @Bean
54      public HandlerInstantiator handlerInstantiator(final ApplicationContext applicationContext) {
55          return new SpringHandlerInstantiator(applicationContext.getAutowireCapableBeanFactory());
56      }
57  }