DWR目前不支持CDI,所以无法得到@Inject bean。
我的解决办法是,使用apache deltaspike,她是CDI的一个扩展。
看下面这个例子
1、dwr调用Test,而Test方法中注入了一个User user实例。
--------------------------------
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.deltaspike.core.api.provider.BeanProvider;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
@Named("Test")
@RemoteProxy //for dwr
public class Test
{
@Inject private User user;
@RemoteMethod //for dwr
public String test(){
//dwr不能得到 @Inject bean
System.out.println("user is null ? "+(user == null));
//但是用手工方式可以
user=BeanProvider.getContextualReference(User.class,false);
System.out.println("user name is: "+user.getUsername());
return user.getUsername();
}
}
------------------------------------
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@SessionScoped
@Named
public class User implements Serializable{
private static final long serialVersionUID = -559381017984772756L;
private String username="wuhenge";
public String getUsername(){
return this.username;
}
public void setUsername(String s){
this.username=s;
}
}
-------------------------------
user=BeanProvider.getContextualReference(User.class,false);这就是手工方式获得注入bean的办法。
2、调用方法
-------------------------
<!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">
<head>
<script type='text/javascript' src='dwr/engine.js'></script>
<script type='text/javascript' src='dwr/util.js'></script>
<script type='text/javascript' src='dwr/interface/Test.js'></script>
</head>
<h:form id="loginForm">
<p>for dwr:</p>
<input type="button" value="dwr" οnclick="Test.test(function(i){alert(i);});"/>
</h:form>
</html>
--------------------------
据说BeanProvider.injectFields(this) 可以获取所有依赖,但我没试过。