“@ inject”-ed属性保持为null [英] "@inject"-ed attribute remains null
问题描述
我正在尝试将服务注入到我的bean中,但它总是 null
。
我收到以下错误:WELD-001000错误解析属性userBean对基础null。
I am trying to inject a service into my bean but it is always null
.
I get the following error: WELD-001000 Error resolving property userBean against base null.
一些代码片段:
index.xhtml
index.xhtml
<h:body>
Hello from Facelets
#{userBean.name}
</h:body>
userbean.java
userbean.java
package beans;
import Domain.User;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import service.UserService;
@Named
@SessionScoped
public class UserBean implements Serializable{
@Inject UserService service;
private User user;
public UserBean(){
this.user = service.find_user("foo");
}
public String getName(){
return "bar";
}
}
UserService.java
UserService.java
package service;
import Domain.User;
import javax.ejb.Stateless;
import javax.inject.Named;
@Named
@Stateless
public class UserService {
public UserService(){}
public User find_user(String name){
return new User();
}
}
推荐答案
错误消息可能是一个提示,JVM无法创建 UserBean
的实例。以下是一些猜测,必须证明:
The error message could be a hint, that the JVM wasn't able to create an instance of UserBean
. The following is some guessing and would have to be proven:
Dependecy Injection需要一个依赖注入器,一个注入 <$ em>实例的工具c $ c> UserService 进入 UserBean
。在你的代码中,你已经在bean的实例化过程中使用了这个注入的实例:你在构造函数中调用注入的服务。
Dependecy Injection requires a dependency injector, a tool that injects an instance of UserService
into a UserBean
. In your code you're already using this injected instance during instantiation of the bean: you call the injected service in the constructor.
如果依赖注入器启动它的工作在创建bean之后,然后对构造函数内部服务的调用将引发 NullPointerException
(因为 service
当时仍为 null
)。通过尝试在 UserBean
构造函数中捕获NPE一会儿值得检查。如果你抓住一个 - il - 依赖注入器在创建bean之后开始运行,因此,我们不能在类实例化期间使用注入的服务(=在构造函数中)
If the dependency injector starts it's work after the bean is created, then the call to the service inside the constructor will raise a NullPointerException
(because service
is still null
at that time). It's worth checking that by trying to catch NPEs in the UserBean
constructor for a moment. If you catch one - voilà - the dependency injector starts runnning after the bean has been created and, as a consequence, we can't use injected services during class instantiation (= in the constructor)
解决方法想法:实现一个小型服务提供商助手类 - 内部类可以工作:
Workaround idea: implement a small service provider helper class - inner class could work:
public class UserBean implements Serializable {
static class UserServiceProvider {
@Inject static UserService service;
}
// ...
public UserBean() {
this.user = UserServiceProvider.service.findUser("kaas");
}
// ...
}
未经测试但可以正常工作 - 在中使用bean构造函数之前,应该在提供程序类中注入服务。
Untested but could work - the service should be injected in the provider class before you use it in the beans constructor.
这篇关于“@ inject”-ed属性保持为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!