以下代码显示了如何进行bean注入。
我们先定义一个消息bean,它有一个字符串属性来存储消息。
@ManagedBean(name="message")
@SessionScoped
public class MessageBean implements Serializable {
private static final long serialVersionUID = 1L;
private String sayWelcome = "Welcome to JSF 2.0";
然后我们再定义另一个托管bean,并使用@ManagedProperty
注解注入MessageBean
。
@ManagedBean
@SessionScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 1L;
@ManagedProperty(value="#{message}")
private MessageBean messageBean;
public void setMessageBean(MessageBean messageBean) {
this.messageBean = messageBean;
}
实例
打开 NetBean8.2,创建一个名为: InjectManagedBeans 的工程,并加入以下文件代码。
以下是文件:UserBean.java 中的代码 -
package com.yiibai;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 1L;
@ManagedProperty(value="#{message}")
private MessageBean messageBean;
public void setMessageBean(MessageBean messageBean) {
this.messageBean = messageBean;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSayWelcome(){
//check if null?
if("".equals(name) || name ==null){
return "";
}else{
return messageBean.getSayWelcome() + name;
}
}
}
以下是是文件:index.xhtml 中的代码 -
<?xml version="1.0" encoding="UTF-8"?>
<!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:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:form>
<h:inputText id="name" value="#{userBean.name}"></h:inputText>
<h:commandButton value="Welcome Me">
<f:ajax execute="name" render="output" />
</h:commandButton>
<h2><h:outputText id="output" value="#{userBean.sayWelcome}" /></h2>
</h:form>
</h:body>
</html>
以下是文件:MessageBean.java 中的代码 -
package com.yiibai;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean(name="message")
@SessionScoped
public class MessageBean implements Serializable {
private static final long serialVersionUID = 1L;
private String sayWelcome = "Welcome to JSF 2.0";
public String getSayWelcome() {
return sayWelcome;
}
public void setSayWelcome(String sayWelcome) {
this.sayWelcome = sayWelcome;
}
}
运行测试结果
Tomcat启动完成后,在浏览器地址栏中输入以下URL。
http://localhost:8084/InjectManagedBeans/
运行结果如下所示 -