繁体   English   中英

使用Spring Boot 2.1.0的杰克逊解串器转换器中的@Autowired依赖关系为null

[英]@Autowired dependency in jackson deserializer converter with Spring Boot 2.1.0 is null

我想将spring依赖项自动连接到杰克逊反序列化转换器中。 例如,

 import com.fasterxml.jackson.databind.util.StdConverter;

 @Component
 public class LookupConverter extends StdConverter<T, T> {

    @Autowired
    private Repository<T> repo;

    @Override
    public IsoCountry convert(T value) {
        repo.findById(value.getId()).orElse(value);
    }
}

我试过使用: SpringBeanAutowiringSupport例如,

public LookupConverter() {
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}

但收到以下消息

当前WebApplicationContext不可用于处理LookupConverter:确保在Spring Web应用程序中构造了此类。 无需注射即可继续。

我尝试将SpringHandlerInstantiator注入ObjectMapper ala thisthis

@Bean
public HandlerInstantiator handlerInstantiator(ApplicationContext applicationContext) {
    return new SpringHandlerInstantiator(applicationContext.getAutowireCapableBeanFactory());
}

@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder(HandlerInstantiator handlerInstantiator) {
    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
    builder.handlerInstantiator(handlerInstantiator);
    return builder;
}

这也行不通,似乎是因为未使用SpringHandlerInstantiator并且未在spring实例化我的自定义Converter

任何使用Spring Boot 2.1.0如何完成此操作的指针将不胜感激。

解决此问题的一种方法是创建@Service ,它以静态方式提供一个或多个存储库,例如:

@Service
public class RepositoryService {

    @Resource
    private ExampleEntityRepository repo;

    @Getter
    private static final Map<Class<?>, Repository<?, ?>> repos = new HashMap<>();

    @PostConstruct
    private void postConstruct() {
        repos.put(ExampleEntity.class, repo);
    }

}

然后,除了将回购注入您的转换器,您将执行以下操作:

private Repository<ExampleEntity, Long> repo = RepositoryService.getRepos()
                                                       .get(ExampleEntity.class);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM