Micronaut中使用@Named限定符无法注入不同Bean的问题
问题原因
你的注入写法不符合限定符的使用规范:@Named注解标注在setter方法上不会生效,该注解需要标注在注入参数上才能正确匹配对应名称的Bean,导致Micronaut给两个setter都注入了默认的全局ObjectMapper实例,所以两个成员变量指向同一个对象。
解决方法
写法1:调整setter注入的注解位置
将@Named注解从setter方法移到方法的入参上即可:
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 public void setJsonMapper(@Named("jsonObjectMapper") ObjectMapper jsonMapper) { this.jsonMapper = jsonMapper; } @Inject public void setYamlMapper(@Named("yamlObjectMapper") ObjectMapper yamlMapper) { this.yamlMapper = yamlMapper; } // 省略其他业务代码 }
写法2:使用字段注入(更简洁)
直接将@Inject和@Named标注在成员变量上,不需要写setter方法:
import jakarta.inject.Inject; import jakarta.inject.Named; import jakarta.inject.Singleton; @Singleton public class MyServiceImpl implements MyService { @Inject @Named("jsonObjectMapper") private ObjectMapper jsonMapper; @Inject @Named("yamlObjectMapper") private ObjectMapper yamlMapper; // 省略其他业务代码 }
可选优化(避免潜在的类型匹配问题)
如果调整注入写法后仍有问题,可以在工厂类的Bean生产方法上加上@Typed注解明确Bean类型,避免Micronaut类型推断异常:
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 io.micronaut.context.annotation.Typed; import jakarta.inject.Named; import jakarta.inject.Singleton; @Factory public class MyObjectMapper { @Singleton @Named("jsonObjectMapper") @Typed(ObjectMapper.class) public ObjectMapper getJsonObjectMapper() { return new ObjectMapper(new JsonFactory()); } @Singleton @Named("yamlObjectMapper") @Typed(ObjectMapper.class) public ObjectMapper getYamlObjectMapper() { return new ObjectMapper(new YAMLFactory()); } }
内容的提问来源于stack exchange,提问作者QuocNg
相关产品推荐
相关产品推荐

