【问题标题】:Unable to get CDI and JAX-RS to work together in Glassfish无法让 CDI 和 JAX-RS 在 Glassfish 中协同工作
【发布时间】:2018-07-24 23:05:33
【问题描述】:

我必须将一个在 Wildfly 中成功运行的项目部署到 Glassfish。除了 ResponseFilter 中的对象的依赖注入之外,一切都运行良好。该对象在 REST 资源处理程序中生成。我创建了一个简单的项目来演示这个问题。我在 Stackoverflow 上浏览了几个答案。尝试了一切,似乎没有一个工作。

bean.xml

<beans
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
    bean-discovery-mode="all">
</beans>

App.java

@ApplicationPath("api")
public class App extends Application {
}

DemoResource.java

@Path("/demo")
public class DemoResource {

    @Produces
    private Pojo pojo;

    @GET
    public void demo() {
        pojo = new Pojo();
    }
}

Pojo.java

@Alternative
public class Pojo {
    protected String firstName;
    protected String lastName;
}

ResponseFilter.java

@Provider
public class ResponseFilter implements ContainerResponseFilter {

    @Inject
    private Pojo injectedPojo;

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

        Instance<Pojo> instance = CDI.current().select(Pojo.class);
        Pojo uninjectedPojo = null;
        if (!instance.isUnsatisfied() && instance.get() != null)
            uninjectedPojo = instance.get();
        System.out.println("Injected POJO: " + injectedPojo);
        System.out.println("Uninjected POJO: " + uninjectedPojo);
    }
}

Wildfly 日志文件中的输出为:

16:33:58,765 INFO  [stdout] (default task-3) Injected POJO: com.example.demo.Pojo@2092c78b
16:33:58,765 INFO  [stdout] (default task-3) Uninjected POJO: com.example.demo.Pojo@2092c78b

Glassfish 日志中的输出为:

[2018-02-14T16:36:37.730+0545] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=27 _ThreadName=http-thread-pool::http-listener-1(3)] [timeMillis: 1518605497730] [levelValue: 800] [[Injected POJO: null]]
[2018-02-14T16:36:37.730+0545] [Payara 4.1] [INFO] [] [] [tid: _ThreadID=27 _ThreadName=http-thread-pool::http-listener-1(3)] [timeMillis: 1518605497730] [levelValue: 800] [[Uninjected POJO: null]]

【问题讨论】:

    标签: glassfish jax-rs cdi java-ee-7


    【解决方案1】:

    &lt;alternatives&gt; 声明添加到beans.xml

    <beans ... >
        <alternatives>
            <class>[package name].Pojo</class>
        </alternatives>
    </beans>
    

    或添加

    @Priority(Interceptor.Priority.APPLICATION+100)
    

    Pojo 类的注解

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 2015-05-02
      • 2015-12-16
      • 2012-05-19
      • 2012-12-29
      • 1970-01-01
      相关资源
      最近更新 更多