【发布时间】:2021-09-23 16:54:13
【问题描述】:
我已经定义了一个 ObjectMapper 工厂类,如下所示:
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import io.micronaut.context.annotation.Factory;
import jakarta.inject.Named;
import jakarta.inject.Singleton;
@Factory
public class MyObjectMapper {
@Singleton
@Named("jsonObjectMapper")
public ObjectMapper getJsonObjectMapper() {
return new ObjectMapper(new JsonFactory());
}
@Singleton
@Named("yamlObjectMapper")
public ObjectMapper getYamlObjectMapper() {
return new ObjectMapper(new YAMLFactory());
}
}
然后,在客户端类上,我尝试像这样注入它们:
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.inject.Singleton;
@Singleton
public class MyServiceImpl implements MyService {
private ObjectMapper jsonMapper;
private ObjectMapper yamlMapper;
@Inject
@Named("jsonObjectMapper")
public void setJsonMapper(ObjectMapper jsonMapper) {
this.jsonMapper = jsonMapper;
}
@Inject
@Named("yamlObjectMapper")
public void setYamlMapper(ObjectMapper yamlMapper) {
this.yamlMapper = yamlMapper;
}
...
我的目标是让 jsonMapper 在 MyObjectMapper 类上由带有 @Named("jsonObjectMapper") 的 bean 注入,并在 yamlMapper 和 @Named("yamlObjectMapper") 上注入。但是,当我尝试调试时,jsonMapper 和yamlMapper 具有相同的引用,这意味着它们是由同一个 ObjectMapper 注入的。我的问题是如何在 Micronaut 上为 json 和 yaml 映射器注入 2 个不同的 bean?
谢谢!
【问题讨论】:
标签: java dependency-injection micronaut