我正在尝试将ObjectMapper类的实例注入到我的JAX-RS资源中,但是看到此错误,

[ERROR   ] Api type [com.fasterxml.jackson.databind.ObjectMapper] is not found with the qualifiers
Qualifiers: [@javax.enterprise.inject.Default()]
for injection into Field Injection Point, field name :  mapper, Bean Owner : [PageMetaResource, Name:null, WebBeans Type:MANAGED, API Types:[com.lmig.pi.ado.meta.resources.PageMetaResource], Qualifiers:[javax.enterprise.inject.Any,javax.enterprise.inject.Default]]


我在WEB-INF目录中有一个空的beans.xml文件,

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>


我想知道我的Application.getSingletons()方法是否引起了这个问题,

@Override
public Set<Object> getSingletons()
{
    Set<Object> set = new HashSet<>();

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    ObjectMapper mapper = new ObjectMapper();

    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setDateFormat(df);

    JacksonJsonProvider provider = new JacksonJsonProvider();
    provider.setMapper(mapper);

    set.add(provider);

    return set;
}


我的资源类看起来像这样,

public class PageMetaResource extends BasePresentationResource
{
    /**
     * The logger of the class
     */
    private static final Logger logger = Logger.getLogger(PageMetaResource.class);

    /**
     * Factory that produces a {@link PageMetaServices} instance for this resource.
     */
    private ServiceFactory serviceFactory;

    /**
     * Factory that produces a {@link PageMetaResourceBean} instance for this resource.
     */
    private ResourceBeanFactory resourceBeanFactory;

    /**
     * The servlet context.
     */
    @Context
    private ServletContext context;

    @Inject
    private ObjectMapper mapper;

    /**
     * Constructor
     */
    @Inject
    public PageMetaResource(ServiceFactory serviceFactory, ResourceBeanFactory resourceBeanFactory)
    {
        this.serviceFactory = serviceFactory;
        this.resourceBeanFactory = resourceBeanFactory;
    }
...
}


有任何想法吗?我试图@inject到构造函数中-但引发了类似的错误。

谢谢您的帮助,

安德鲁

PS:我正在部署到Websphere Application Server v8.5 Liberty Profile

最佳答案

您的CDI容器找不到ObjectMapper的生产者。看看here

关于java - 如何@ fastfast.jackson.ObjectMapper注入(inject)JAX-RS资源?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25038908/

10-12 03:10