尝试访问 Bean 时为空指针

Null pointer while trying to access Bean

我有一个创建多个 bean 的配置 class:

@Configuration
public class TopLevelConfig {
    @Bean
    public MyMapper myMapper() {
        MyMapper mapper = new MyMapper();
        mapper.registerModule(new MetadataModule());
        return new MyMapper();
    }
}

现在在 MetadataModule 中:

@Override
public void setupModule(final SetupContext setupContext) {
    final SimpleDeserializers deserializers = new SimpleDeserializers();

    deserializers.addDeserializer(Payload.class, new PayloadDeserializer());
    setupContext.addDeserializers(deserializers);
}

PayloadDeserializer 中,我无法自动装配 MyMapper class。我在想这是因为当 PayloadDeserializer 的新对象被创建时,MyMapper 的 bean 还没有被创建。如何允许 PayloadDeserializer 访问 bean 对象?

您正在通过调用new PayloadDeserializer()自己创建PayloadDeserializer对象,这就是MyMapper没有被注入的原因。要 inject/autowire 工作,您的 bean 应该 spring 管理。为此,您可以在 PayloadDeserializer class 之上使用 @Component,如下所示。

@Component
public class PayloadDeserializer {
    private final MyMapper mapper;

    @Autowired
    public PayloadDeserializer(MyMapper mapper) {
        this.mapper = mapper;
    }
}

@Configuration
public class TopLevelConfig {
    @Bean
    public MyMapper myMapper(PayloadDeserializer payloadDeserializer) {
        MyMapper mapper = new MyMapper();
        mapper.registerModule(metadataModule(payloadDeserializer));
        return mapper;
    }

    @Bean
    public MetadataModule metadataModule(PayloadDeserializer payloadDeserializer) {
        return new MetadataModule(payloadDeserializer);
    }
}

public class MetadataModule {
    private final PayloadDeserializer payloadDeserializer;
    public MetadataModule(PayloadDeserializer payloadDeserializer) {
        this.payloadDeserializer = payloadDeserializer;
    }

    @Override
    public void setupModule(final SetupContext setupContext) {
        final SimpleDeserializers deserializers = new SimpleDeserializers();

        deserializers.addDeserializer(Payload.class, payloadDeserializer);
        setupContext.addDeserializers(deserializers);
    }
}