CDI(Contexts and Dependency Injection 上下文依赖注入),是JAVA官方提供的依赖注入实现,可用于Dynamic Web Module中,先给3篇老外的文章,写得很不错

1、Java EE CDI Dependency Injection (@Inject) tutorial
2、Java EE CDI Producer methods tutorial
3、Java EE CDI bean scopes

此外,还有jboss官方的参考文档:http://docs.jboss.org/weld/reference/latest/en-US/html/

如果不想啃洋文,也可以继续往下看:

一、基本的Inject注入

1.1 在eclipse中先创建一个常规的maven Dynamic Web项目(不熟悉maven的,可以先看看这里),下面是完整的项目截图

里面各package的代码,后面会给出。 项目的属性中,注意有几个属性要勾上(默认情况下,应该已经自动勾上了),如下图:

上图右侧的圆圈,其实就是CDI 1.0使用的先决条件。

Pom.xml的内容如下:

 <?xml version="1.0" encoding="UTF-8"?>
<!--
JBoss, Home of Professional Open Source
Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
contributors by the @authors tag. See the copyright.txt in the
distribution for a full listing of individual contributors. Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>cnblogs</groupId>
<artifactId>cdi-web-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>cdi-web-sample</name>
<description>A starter Java EE 6 webapp project for use on JBoss AS 7 / EAP 6, generated from the jboss-javaee6-webapp archetype</description> <url>http://jboss.org/jbossas</url>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<distribution>repo</distribution>
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
</license>
</licenses> <properties>
<!-- Explicitly declaring the source encoding eliminates the following
message: -->
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- JBoss dependency versions -->
<version.jboss.maven.plugin>7.4.Final</version.jboss.maven.plugin> <!-- Define the version of the JBoss BOMs we want to import to specify
tested stacks. -->
<version.jboss.bom>1.0.7.Final</version.jboss.bom>
<!-- Alternatively, comment out the above line, and un-comment the line
below to use version 1.0.4.Final-redhat-4 which is a release certified to
work with JBoss EAP 6. It requires you have access to the JBoss EAP 6
maven repository. -->
<!-- <version.jboss.bom>1.0.4.Final-redhat-4</version.jboss.bom>> --> <!-- other plugin versions -->
<version.surefire.plugin>2.10</version.surefire.plugin>
<version.war.plugin>2.1.1</version.war.plugin> <!-- maven-compiler-plugin -->
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.6</maven.compiler.source>
</properties> <dependencyManagement>
<dependencies>
<!-- JBoss distributes a complete set of Java EE 6 APIs including a Bill
of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection)
of artifacts. We use this here so that we always get the correct versions
of artifacts. Here we use the jboss-javaee-6.0-with-tools stack (you can
read this as the JBoss stack of the Java EE 6 APIs, with some extras tools
for your project, such as Arquillian for testing) and the jboss-javaee-6.0-with-hibernate
stack you can read this as the JBoss stack of the Java EE 6 APIs, with extras
from the Hibernate family of projects) -->
<dependency>
<groupId>org.jboss.bom</groupId>
<artifactId>jboss-javaee-6.0-with-tools</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.jboss.bom</groupId>
<artifactId>jboss-javaee-6.0-with-hibernate</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <dependencies> <!-- First declare the APIs we depend on and need for compilation. All
of them are provided by JBoss AS 7 --> <!-- Import the CDI API, we use provided scope as the API is included in
JBoss AS 7 -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency> <!-- Import the Common Annotations API (JSR-250), we use provided scope
as the API is included in JBoss AS 7 -->
<dependency>
<groupId>org.jboss.spec.javax.annotation</groupId>
<artifactId>jboss-annotations-api_1.1_spec</artifactId>
<scope>provided</scope>
</dependency> <!-- Import the JAX-RS API, we use provided scope as the API is included
in JBoss AS 7 -->
<dependency>
<groupId>org.jboss.spec.javax.ws.rs</groupId>
<artifactId>jboss-jaxrs-api_1.1_spec</artifactId>
<scope>provided</scope>
</dependency> <!-- Import the JPA API, we use provided scope as the API is included in
JBoss AS 7 -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<scope>provided</scope>
</dependency> <!-- Import the EJB API, we use provided scope as the API is included in
JBoss AS 7 -->
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.1_spec</artifactId>
<scope>provided</scope>
</dependency> <!-- JSR-303 (Bean Validation) Implementation -->
<!-- Provides portable constraints such as @Email -->
<!-- Hibernate Validator is shipped in JBoss AS 7 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency> <!-- Import the JSF API, we use provided scope as the API is included in
JBoss AS 7 -->
<dependency>
<groupId>org.jboss.spec.javax.faces</groupId>
<artifactId>jboss-jsf-api_2.1_spec</artifactId>
<scope>provided</scope>
</dependency> <!-- Now we declare any tools needed --> <!-- Annotation processor to generate the JPA 2.0 metamodel classes for
typesafe criteria queries -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<scope>provided</scope>
</dependency> <!-- Annotation processor that raising compilation errors whenever constraint
annotations are incorrectly used. -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<scope>provided</scope>
</dependency> <!-- Needed for running tests (you may also use TestNG) -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency> <!-- Optional, but highly recommended -->
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA)
JPA from JUnit/TestNG -->
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.jboss.arquillian.protocol</groupId>
<artifactId>arquillian-protocol-servlet</artifactId>
<scope>test</scope>
</dependency> </dependencies> <build>
<!-- Maven will append the version to the finalName (which is the name
given to the generated war, and hence the context root) -->
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<!-- Java EE 6 doesn't require web.xml, Maven needs to catch up! -->
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<!-- The JBoss AS plugin deploys your war to a local JBoss AS container -->
<!-- To use, run: mvn package jboss-as:deploy -->
<plugin>
<groupId>org.jboss.as.plugins</groupId>
<artifactId>jboss-as-maven-plugin</artifactId>
<version>${version.jboss.maven.plugin}</version>
</plugin>
</plugins>
</build> <profiles>
<profile>
<!-- The default profile skips all tests, though you can tune it to run
just unit tests based on a custom pattern -->
<!-- Seperate profiles are provided for running all tests, including Arquillian
tests that execute in the specified container -->
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.surefire.plugin}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile> <profile>
<!-- An optional Arquillian testing profile that executes tests in your
JBoss AS instance -->
<!-- This profile will start a new JBoss AS instance, and execute the
test, shutting it down when done -->
<!-- Run with: mvn clean test -Parq-jbossas-managed -->
<id>arq-jbossas-managed</id>
<dependencies>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-arquillian-container-managed</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile> <profile>
<!-- An optional Arquillian testing profile that executes tests in a remote
JBoss AS instance -->
<!-- Run with: mvn clean test -Parq-jbossas-remote -->
<id>arq-jbossas-remote</id>
<dependencies>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-arquillian-container-remote</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile> <profile>
<!-- When built in OpenShift the 'openshift' profile will be used when
invoking mvn. -->
<!-- Use this profile for any OpenShift specific customization your app
will need. -->
<!-- By default that is to put the resulting archive into the 'deployments'
folder. -->
<!-- http://maven.apache.org/guides/mini/guide-building-for-different-environments.html -->
<id>openshift</id>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<outputDirectory>deployments</outputDirectory>
<warName>ROOT</warName>
</configuration>
</plugin>
</plugins>
</build>
</profile> </profiles>
</project>

pom.xml

1.2 model包下,会创建Product类

 package model;

 public class Product {

     private String productName;

     private String productNo;

     public String getProductNo() {
return productNo;
} public void setProductNo(String productNo) {
this.productNo = productNo;
} public String getProductName() {
return productName;
} public void setProductName(String productName) {
this.productName = productName;
} public String toString() {
return this.productName + " " + this.productNo; }
}

Product

这个类其实是打酱油的

1.3 service包下,建一个ProductService接口

 package service;

 import model.Product;

 public interface ProductService {

     Product getNewProduct();

 }

ProductService

1.4 service包下,再来几个实现

 package service;

 import javax.inject.Inject;

 import model.Product;

 public abstract class BaseProductServiceImpl implements ProductService {

     @Inject
protected Product product; public abstract Product getNewProduct();
}

BaseProductServiceImpl

这个是实现类的基类,注意这里私有成员上打了一个注解@Inject,表示运行时将动态注入(实例化)一个Product

再来二个具体的实现类,BookProductServiceImpl生成"书籍"

 package service;

 import annotation.Book;
import model.Product; @Book
public class BookProductServiceImpl extends BaseProductServiceImpl { public Product getNewProduct() {
product.setProductName("论程序员的自我修养");
product.setProductNo("ISBN 999");
return product;
} }

BookProductServiceImpl

TelephoneProductServiceImpl生成“电话”

 package service;

 import annotation.Telephone;
import model.Product; @Telephone
public class TeletephoneProductServiceImpl extends BaseProductServiceImpl { public Product getNewProduct() {
product.setProductName("NOKIA LUMIA");
product.setProductNo("920");
return product;
} }

TeletephoneProductServiceImpl

可能有朋友注意到了,里面用到了二个自己写的注释@Book和@Telephone,接下来会讲到,这里先忽略

1.5 controller包下,添加IndexController类

为了能跟JSF的前台页面交互,这里需要添加一个Controller

 package controller;

 import javax.faces.bean.ManagedBean;
import javax.inject.Inject; import annotation.*;
import service.*; @ManagedBean(name = "Index")
public class IndexController { @Inject
@Book
private ProductService bookProductService; @Inject
@Telephone
private ProductService telephoneProductService; public ProductService getBookProductService() {
return bookProductService;
} public ProductService getTelephoneProductService() {
return telephoneProductService;
} }
IndexController

IndexController

好了,一下子搞了这么多代码,先停下来消化一下,这里我们模拟了分层架构:

model - 代表了业务模型层(本例中,为了简单起见,没有细分 业务模型、实体模型、以及web中的ViewModel)

service - 代表了服务层(为了简单起见,我们把接口+实现都放在一起了,实际中,可能会把这二个分开来)

controller - 这是web层MVC中的控制器层

当然,为了能展示最终的效果,我们会在后面加一个页面做为View层来提供UI

1.6 webapp下,新建一个index.xhtml文件,内容如下:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"> <h:head></h:head>
<body>
Book:
<br /> #{Index.bookProductService.newProduct.toString()}
<br />
<br /> Telephone:
<br /> #{Index.telephoneProductService.newProduct.toString()}
</body>

index.xhtml

页面里几乎没啥代码,就是调用IndexController实例中的getBookProductService、getTelephoneProductService方法,进而得到相应的"服务实现类实例",最终输出产品信息

1.7 Inject用在什么地方了?

a) 页面显示时,IndexController里,bookProductService和telephoneProductService这二个私有成员上,都加了@Inject注解,所以运行时,这二个成员都能被实例化,但是问题来了,它们都是ProductService的接口类型,而这个接口有二个具体的实现(BookProductServiceImpl和TeletephoneProductServiceImpl),最终运行时,应该实现化哪一个呢?

关键在于另一个注解@Book和@Telephone,观察一下:BookProductServiceImpl类上我们也加了@Book,而TeletephoneProductServiceImpl上加了@Telephone,这样正好可以跟IndexControll中这二个私成成员的注释“匹配”上,所以最终系统知道私有成员bookProductService应该被实例化成BookProductServiceImpl,telephoneProductService被实例化成TeletephoneProductServiceImpl

@Book和@Telephone的代码如下:

 package annotation;

 import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy; import javax.inject.Qualifier; @Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface Book { }

Book

 package annotation;

 import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import javax.inject.Qualifier; @Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface Telephone { }

Telephone

b) BaseProductServiceImpl中,在私成成员product上加了@Inject,这样运行时,能自动实例化Product对象

1.8 运行结果

jboss中部署后,浏览http://localhost:8080/cdi-web-sample/faces/index.xhtml 或http://localhost:8080/cdi-web-sample/index.jsf

1.9 Method(方法)注入及Constructor(构造器)注入

刚才我们看到的都是在Field(成员)上注入,除了这种方式,也可以在Method或Constructor上注入

     private Product product ;

     /**
* 演示在方法上使用@Inject注入
* @param p
*/
@Inject
public void setProduct(Product p){
product = p;
} public Product getProduct(){
return product;
}

Method Inject

上面的代码即是Method注入的示例,最后来看下构造器注入,我们再新建一个ClothProductServiceImpl用于生产服装

 package service;

 import javax.inject.Inject;

 import annotation.*;
import model.Product; @Cloth
public class ClothProductServiceImpl implements ProductService { private Product product; /**
* 构造器注入
* @param p
*/
@Inject
public ClothProductServiceImpl(Product p ){
p.setProductName("A New Dress");
p.setProductNo("SPRIT-001");
product = p; } public Product getNewProduct() {
return product;
} }

Constructor Inject

运行时,系统会自动给构造器ClothProductServiceImpl传递一个实例化的Product对象作为参数,以实现Product实例的注入

附文中示例源码下载:cdi-web-sample.zip

下一节,我们将学习Bean注入后的生命周期管理

最新文章

  1. centos7.0 安装LNMP运行环境
  2. 2015 Multi-University Training Contest 1 - 1002 Assignment
  3. 在HCI层看从inquiry的整个过程
  4. c语言实现词频统计
  5. 基于PBOC电子钱包的圈存过程详解
  6. Google Map API v2 步步为营 (二)----- Location
  7. C模块划分
  8. 关于使用iframe标签自适应高度的使用
  9. 漫谈项目设计&amp;重构&amp;性能优化
  10. [SDOI2011]工作安排
  11. QTableView
  12. Windows10文件目录下添加 Shift+右键打开管理员Powershell窗口
  13. AngularJS 最常用的八种功能
  14. mySQL的行转列
  15. php list()函数
  16. arch 相关软件及脚本
  17. Django01-Django基础
  18. Unity Jobsystem 详解实体组件系统ECS
  19. Kaggle 自行车租赁预测比赛项目实现
  20. Android-Start方式和Bind方式混合开启Service

热门文章

  1. symfony2 安装并创建第一个页面
  2. 关于NodeJS的思考
  3. Cookie/Session机制
  4. Java开发人员最常犯的10个错误
  5. luemn PHP_CodeSniffer的安装
  6. maven 安装alipay-sdk包到本地及远程仓库
  7. 从键盘上输入一个正整数n,请按照以下五行杨辉三角形的显示方式, 输出杨辉三角形的前n行。请采用循环控制语句来实现。
  8. centos7安装CDH5.5.0
  9. Linux下使用NDK编译FFMPEG(libstagefright)
  10. db2存储过程