JBoss 系列七十:一个简单的 CDI Web 应用

概述

本文通过一个简单的 CDI Web 应用演示dependency injection, scope, qualifiers 以及EL整合。应用部署完成后我们可以通过http://localhost:8080/moodchecker 来访问Web 应用欢迎页面,Mood在good和bad之间不停变化。通过本文,我们可以明白how qualifiers influence the selection of an injector。

编译部署测试应用

本应用源代码位于 https://github.com/kylinsoong/webframework/tree/master/cdi/moodchecker

我们可以使用软件安装及资料下载中描述的方法下载,编译生成部署包cdi-moodchecker.war,使用使用4种方式部署应用到JBoss7/WildFly中描述的方法部署cdi-moodchecker.war到JBoss节点。应用部署完成启动JBoss 7如下:

./standalone.sh

应用部署完成后我们可以通过  http://localhost:8080/moodchecker 访问,Web页面显示如下:


示例分析

示例涉及到的配置文件或java类包括:

  • beans.xml
  • faces-config.xml
  • index.xhtml
  • web.xml
  • jboss-web.xml
  • org.jboss.demo.cdi.moodchecker.Mood
  • org.jboss.demo.cdi.moodchecker.BadMood
  • org.jboss.demo.cdi.moodchecker.GoodMood
  • org.jboss.demo.cdi.moodchecker.MoodChecker

Mood

Mood类内容如下:

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@RequestScoped
public class Mood {

	private String mood;
	
	@Inject
	@Good
	private MoodChecker moodChecker;

	public Mood() {

	}

	public void check() {
		mood = moodChecker.checkMood();
	}

	public String getMood() {
		return mood;
	}
}

注意:@Named 和 @RequestScoped标注类本身,MoodChecker属性使用@Inject和@Good注入。

Qualifiers

注意前面Good是我们自定义的标注,用来注入GoodMood,我们这里创建了两个标注,Good和Bad,如下:

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.inject.Qualifier;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Qualifier
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
public @interface Good {

}

我们使用 Good标注GoodMood,如下所示:

@Good
public class GoodMood implements MoodChecker {

	public String checkMood() {
		return "I feel great !";
	}

}

这样当在 Mood中使用@Good标注时会注入GoodMood。

EL整合

index.xhtml使用EL表达式与后台Bean Mood直接交互,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">

<h:head>
	<title>How Are You Today?</title>
</h:head>
<h:body>
	<h3>How Are You?</h3>
	<h:form>
		<p>
			<h:commandButton value="Check Mood" action="#{mood.check}" />
		</p>
		<p>
			<h:outputText value="#{mood.mood}" />
		</p>

	</h:form>
</h:body>

</html>





转载于:https://my.oschina.net/iwuyang/blog/197250

猜你喜欢

转载自blog.csdn.net/weixin_33969116/article/details/91897359
CDI