With Apache CXF 3.0 just being released a couple of weeks ago, the project makes yet another important step to fulfill the JAX-RS 2.0 specification requirements: integration with CDI 1.1. In this blog post we are going to look on a couple of examples of how Apache CXF 3.0 and Apache CXF 3.0 work together.

Starting from version 3.0Apache CXF includes a new module, named cxf-integration-cdi which could be added easily to your Apache Maven POM file:

1.<dependency>
2.<groupId>org.apache.cxf</groupId>
3.<artifactId>cxf-integration-cdi</artifactId>
4.<version>3.0.0</version>
5.</dependency>

This new module brings just two components (in fact, a bit more but those are the key ones):

  • CXFCdiServlet: the servlet to bootstrap Apache CXF application, serving the same purpose asCXFServlet and CXFNonSpringJaxrsServlet, ...
  • JAXRSCdiResourceExtension: portable CDI 1.1 extension where all the magic happens

When run in CDI 1.1-enabled environment, the portable extensions are discovered by CDI 1.1 container and initialized using life-cycle events. And that is literally all what you need! Let us see the real application in action.

We are going to build a very simple JAX-RS 2.0 application to manage people using Apache CXF 3.0 andJBoss Weld 2.1, the CDI 1.1 reference implementation. The Person class we are going to use for a person representation is just a simple Java bean:

01.package com.example.model;
02.
03.public class Person{
04.private String email;
05.private String firstName;
06.private String lastName;
07.public Person(){
08.}
09.public Person(final String email, final String firstName, final StringlastName){
10.this.email = email;
11.this.firstName = firstName;
12.this.lastName = lastName;
13.}
14.//getters and setters are ommited
15.//...

As it is quite common now, we are going to run our application inside embedded Jetty 9.1 container and ourStarter class does exactly that:

Please notice the presence of CXFCdiServlet and two mandatory listeners which were added to the context:

  • org.jboss.weld.environment.servlet.Listener is responsible for CDI injections
  • org.jboss.weld.environment.servlet.BeanManagerResourceBindingListener binds the reference to the BeanManager to JNDI location java:comp/env/BeanManager to make it accessible anywhere from the application

With that, the full power of CDI 1.1 is at your disposal. Let us introduce the PeopleService class annotated with @Named annotation and with an initialization method declared and annotated with @PostConstruct just to create one person.

Up to now we have said nothing about configuring JAX-RS 2.0 applications and resources in CDI 1.1enviroment. The reason for that is very simple: depending on the application, you may go with zero-effort configuration or fully customizable one. Let us go through both approaches.

With zero-effort configuration, you may define an empty JAX-RS 2.0 application and any number of JAX-RS 2.0 resources: Apache CXF 3.0 implicitly will wire them together by associating each resource class with this application. Here is an example of JAX-RS 2.0 application:

And here is a JAX-RS 2.0 resource PeopleRestService which injects the PeopleService managed bean:

01.package com.example.rs;
02.
03.import java.util.Collection;
04.
05.import javax.inject.Inject;
06.import javax.ws.rs.DELETE;
07.import javax.ws.rs.DefaultValue;
08.import javax.ws.rs.FormParam;
09.import javax.ws.rs.GET;
10.import javax.ws.rs.POST;
11.import javax.ws.rs.PUT;
12.import javax.ws.rs.Path;
13.import javax.ws.rs.PathParam;
14.import javax.ws.rs.Produces;
15.import javax.ws.rs.QueryParam;
16.import javax.ws.rs.core.Context;
17.import javax.ws.rs.core.MediaType;
18.import javax.ws.rs.core.Response;
19.import javax.ws.rs.core.UriInfo;
20.
21.import com.example.model.Person;
22.import com.example.services.PeopleService;
23.
24.@Path( "/people" )
25.public class PeopleRestService {
26.@Inject private PeopleService peopleService;
27.
28.@Produces( { MediaType.APPLICATION_JSON } )
29.@GET
30.public Collection< Person > getPeople( @QueryParam( "page")@DefaultValue( "1" ) final int page ) {
31.// ...
32.}
33.
34.@Produces( { MediaType.APPLICATION_JSON } )
35.@Path( "/{email}" )
36.@GET
37.public Person getPerson( @PathParam( "email" ) final String email ) {
38.// ...
39.}
40.
41.@Produces( { MediaType.APPLICATION_JSON } )
42.@POST
43.public Response addPerson( @Context final UriInfo uriInfo,
44.@FormParam( "email" ) final String email,
45.@FormParam( "firstName" ) final String firstName,
46.@FormParam( "lastName" ) final String lastName ) {
47.// ...
48.}
49.
50.// More HTTP methods here
51.// ...
52.}

Nothing else is required: Apache CXF 3.0 application could be run like that and be fully functional. The complete source code of the sample project is available on GitHub. Please keep in mind that if you are following this style, only single empty JAX-RS 2.0 application should be declared.

With customizable approach more options are available but a bit more work have to be done. Each JAX-RS 2.0 application should provide non-empty getClasses() or/and getSingletons() collections implementation. However, JAX-RS 2.0 resource classes stay unchanged. Here is an example (which basically leads to the same application configuration we have seen before):

01.package com.example.rs;
02.
03.import java.util.Arrays;
04.import java.util.HashSet;
05.import java.util.Set;
06.
07.import javax.enterprise.inject.Produces;
08.import javax.inject.Inject;
09.import javax.ws.rs.ApplicationPath;
10.import javax.ws.rs.core.Application;
11.
12.import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
13.
14.@ApplicationPath( "api" )
15.public class JaxRsApiApplication extends Application {
16.@Inject private PeopleRestService peopleRestService;
17.@Produces private JacksonJsonProvider jacksonJsonProvider = newJacksonJsonProvider();
18.
19.@Override
20.public Set< Object > getSingletons() {
21.return new HashSet<>(
22.Arrays.asList(
23.peopleRestService,
24.jacksonJsonProvider
25.)
26.);
27.}
28.}

Please notice, that JAXRSCdiResourceExtension portable CDI 1.1 extension automatically creates managed beans for each JAX-RS 2.0 applications (the ones extending Application) and resources (annotated with@Path). As such, those are immediately available for injection (as for example PeopleRestService in the snippet above). The class JacksonJsonProvider is annotated with @Provider annotation and as such will be treated as JAX-RS 2.0 provider. There are no limit on JAX-RS 2.0 applications which could be defined in this way. The complete source code of the sample project using this appoarch is available on GitHub

No matter which approach you have chosen, our sample application is going to work the same. Let us build it and run:

1.&gt; mvn clean package
2.&gt; java -jar target/jax-rs-2.0-cdi-0.0.1-SNAPSHOT.jar

Calling the couple of implemented REST APIs confirms that application is functioning and configured properly. Let us issue the GET command to ensure that the method of PeopleService annotated with @PostConstructhas been called upon managed bean creation.

And here is the example of POST command:

In this blog post we have just scratched the surface of what is possible now with Apache CXF and CDI 1.1integration. Just to mention that embedded Apache Tomcat 7.x / 8.x as well as WAR-based deployments ofApache CXF with CDI 1.1 are possible on most JEE application servers and servlet containers.

Please take a look on official documentation and give it a try!

The complete source code is available on GitHub.

reference :http://java.dzone.com/articles/apache-cxf-30-cdi-11-support

Apache CXF 3.0: CDI 1.1 Support as Alternative to Spring--reference的更多相关文章

  1. Apache CXF实现Web Service(4)——Tomcat容器和Spring实现JAX-RS(RESTful) web service

    准备 我们仍然使用 Apache CXF实现Web Service(2)——不借助重量级Web容器和Spring实现一个纯的JAX-RS(RESTful) web service 中的代码作为基础,并 ...

  2. Apache CXF实现Web Service(5)—— GZIP使用

    Apache CXF实现Web Service(5)-- GZIP使用 参考来源: CXF WebService整合Spring Apache CXF实现Web Service(1)--不借助重量级W ...

  3. NoClassDefFoundError: Could not initialize class org.apache.cxf.jaxrs.provider.ProviderFactory org.springframework.aop.support.AopUtils.isCglibProxyClass

    报错: 2018-05-03 10:35:20 377 ERROR org.apache.juli.logging.DirectJDKLog.log:181 - Servlet.service() f ...

  4. Apache CXF 102 CXF with REST

    前言 续上篇Apache CXF 101,摘抄部分REST概念性知识,以运行实例考察CXF对REST的支持. 目录 1 REST简介 2 工具 3 运行实例 内容 本Spike记录中内容,如无特别指出 ...

  5. Apache CXF 例子

    来自:http://www.cnblogs.com/frankliiu-java/articles/1641949.html Apache CXF 是一个开放源代码框架,是在Xfire 跟Celtix ...

  6. Cxf + Spring3.0 入门开发WebService

    转自原文地址:http://sunny.blog.51cto.com/182601/625540/ 由于公司业务需求, 需要使用WebService技术对外提供服务,以前没有做过类似的项目,在网上搜寻 ...

  7. apache cxf笔记之Spring客户端访问和调用webservice服务

    继续上次的spring服务的问题,这边介绍一种spring配置客户端的方法. 1.src目录下新建client-beans.xml文件 <?xml version="1.0" ...

  8. Apache CXF入门

    CXF简介 Apache CXF = Celtix + XFire,开始叫 Apache CeltiXfire,后来更名为 Apache CXF 了.CXF 继承了 Celtix 和 XFire 两大 ...

  9. 分布式架构探索 - 2. WebService RPC框架之Apache CXF

    Apache CXF是一个开源的WebService RPC框架. 例子: 1. 新建一个maven web项目, 添加pom 如下: <?xml version="1.0" ...

随机推荐

  1. Ajax、Comet、HTML 5 Web Sockets技术比较分析

    最近因为考虑研究B/S结构网站即时消息处理 参考了 JAVA怎么样实现即时消息提醒http://bbs.csdn.net/topics/330015611http://www.ibm.com/deve ...

  2. PowerDesigner从SqlServer 数据库中导入实体模型

    此篇是之前写的,从我的CSDN博客挖过来的- 一.开启数据库服务并配置ODBC数据源 1.开启数据库服务 (1)通过SQL Server Configuration Manager配置工具启动SQL ...

  3. Cxf + Spring3.0 入门开发WebService

    转自原文地址:http://sunny.blog.51cto.com/182601/625540/ 由于公司业务需求, 需要使用WebService技术对外提供服务,以前没有做过类似的项目,在网上搜寻 ...

  4. BZOJ_1208_&_Codevs_1258_[HNOI2004]_宠物收养所_(平衡树/set)

    描述 http://www.lydsy.com/JudgeOnline/problem.php?id=1208 (据说codevs要更新?就不放codevs的地址了吧...) 有宠物和人,每个单位都有 ...

  5. Excel和XML文件导入

    using System;using System.Collections;using System.Collections.Generic;using System.Configuration;us ...

  6. 执行configure报错configure: error: C++ preprocessor "/lib/cpp" fails sanity check

    解决方案: 出现该情况是由于c++编译器的相关package没有安装,以root用户登陆,在终端上执行: # yum install glibc-headers # yum install gcc-c ...

  7. [Entity Framework]获取部分字段的查询

    using (var ObjectContext = new AgentSystemEntities()) { DateTime dt = new DateTime(1997, 1, 1); stri ...

  8. 关于理解《C++ 对象模型》中:把单一元素的数组放在末尾,struct可以拥有可变大小的数组

    这一章在第19页,写的好深奥,我竟然没看明白在说什么--之后再看了几遍,终于明白了. 原文: C程序员的巧计有时候却成为c++程序员的陷阱.例如把单一元素的数组放在一个struct的末尾,于是每个st ...

  9. linux debug (DOS模拟器,模拟debug)

    最近学习王爽那本<汇编语言>,但其实验均为windows环境,需要用到dos.但最为一个unixer,岂能在windows下开发?所以,要用linux下的工具. 汇编器masm可以用gcc ...

  10. C语言volatile关键字

    volatile提醒编译器它后面所定义的变量随时都有可能改变,因此编译后的程序每次需要存储或读取这个变量的时候,都会直接从变量地址中读取数据.如果没有volatile关键字,则编译器可能优化读取和存储 ...