Java 为什么我的实例变量没有被@Inject初始化为null?
A.java DefaultGridpanel.javaJava 为什么我的实例变量没有被@Inject初始化为null?,java,guice,Java,Guice,A.java DefaultGridpanel.java Class A(){ Para1 para1; Para2 para2; // Getting proper Value no issue with this. private void method_A(){ int sortField = service.getValue(); // Getting proper value no issue. if(sortF
Class A(){
Para1 para1;
Para2 para2; // Getting proper Value no issue with this.
private void method_A(){
int sortField = service.getValue(); // Getting proper value no issue.
if(sortField == null){
DefaultGridPanel df = new DefaultGridPanel(para1, para2); // Issue is in this.
}
}
}
公共类DefaultGridPanel{
@注入
私有瞬态提供程序appInstanceProvider;
公共DefaultGridPanel(){
//
//一些初始化
系统输出打印(appInstanceProvider);
setPageSize(getRecordsPerPage());
}
私有整数getRecordsPerPage(){
ApplicationInstance appInstance=appInstanceProvider.get();
//------------这里-------------
//appInstanceProvider获取null并引发nullpointerException。
整数recordsPerPage=0;
if(appInstance!=null){
recordsPerPage=appInstance.getRecordsPerPage();
}
if(recordsPerPage!=null&&recordsPerPage>0){
返回记录页面;
}
否则{
返回Preferences.DEFAULT\u记录\u每页;
}
}
}
为什么我无法使用@Inject初始化appInstanceProvider
为此,我写了J单元
方法1)我正在调用创建新对象的方法A。
我浏览了很多关于堆栈溢出和博客的问题
我得到了新的关键字将不能帮助我太多的工作与@Inject
方法2)我尝试重写configure()并在该绑定中绑定appInstanceProvider。但我还是在变空
请告诉我任何一种新方法或解决方法。为了使
@Inject
有效,必须管理A类
。在此类中,不要实例化DefaultGridPanel
。相反,也要注射它。
我看到的唯一问题是使用参数化构造函数。使用setter设置这些值。DI上下文将为您注入所需的实例。不要自己创造它们!很可能是因为您没有使用DI来实例化DefaultGridPanel
public class DefaultGridPanel{
@Inject
private transient Provider < ApplicationInstance > appInstanceProvider;
public DefaultGridPanel(){
//
//Constructor Some intialization
System.out.print(appInstanceProvider);
setPageSize(getRecordsPerPage());
}
private Integer getRecordsPerPage() {
ApplicationInstance appInstance = appInstanceProvider.get();
//------------Here-------------
// appInstanceProvider getting null and throwing nullpointerException.
Integer recordsPerPage = 0;
if (appInstance != null) {
recordsPerPage = appInstance.getRecordsPerPage();
}
if (recordsPerPage != null && recordsPerPage > 0) {
return recordsPerPage;
}
else {
return Preferences.DEFAULT_RECORDS_PER_PAGE;
}
}
}