标签:context depedency in tomcat cdi injection
这篇教程主要介绍如何在Tomcat中configure Contexts and Depedency Injection.
由于Tomcat并不是一个JavaEE服务器,所以为了使Tomcat获得对CDI的支持必须手动添加一些依赖类库。接下来主要是CDI开发的一些配置和一个简单的CDI实例。
1.Ubuntu 12.04
2 JDK 1.7.0.09
3. Weld 1.1.10
4 Tomcat 7.0.35
在Tomcat环境下开发CDI程序我们必须添加一些CDI实现的依赖类库,这篇教程中我们使用Weld。我们需要的maven依赖配置如下:
<dependencies> <dependency> <groupId>org.jboss.weld.servlet</groupId> <artifactId>weld-servlet</artifactId> <version>1.1.10.Final</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> </dependencies>
在web项目下的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>
最后一步我们在web.xml中配置CDI listener:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Tomcat CDI example</display-name> <listener> <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class> </listener> </web-app>
接下来定义一个要被依赖注入到servlet的bean.
package com.byteslounge.cdi.bean; public interface Service { int doWork(int a, int b); }
package com.byteslounge.cdi.bean; public class ServiceBean implements Service { @Override public int doWork(int a, int b) { return a + b; } }
定义一个servlet来注入我们定义的ServiceBean:
TestServlet.java package com.byteslounge.cdi.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.inject.Inject; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.byteslounge.cdi.bean.Service; @WebServlet(name = "testServlet", urlPatterns = {"/testcdi"}) public class TestServlet extends HttpServlet { private static final long serialVersionUID = 2638127270022516617L; @Inject private Service service; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int a = 2; int b = 3; PrintWriter out = response.getWriter(); out.println("Hello World: " + service.doWork(a, b)); out.close(); } }
源代码下载:configuring-cdi-with-tomcat-example.zip
原文地址:http://www.byteslounge.com/tutorials/configuring-cdi-with-tomcat-example
标签:context depedency in tomcat cdi injection
原文地址:http://blog.csdn.net/leimengyuanlian/article/details/44701697