我无法在下面的类中摆脱这个NullPointerException。我的控制器正在扩展这个类,当我注释掉下面的构造函数时,问题就消失了......我做错了什么?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'contentController' defined in file [C:\Users\bkuhl\JavaProjects\cmt\cmt\target\cmt\WEB-INF\classes\com\site\cmt\web\ContentController.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.fettergroup.cmt.web.ContentController]: Constructor threw exception; nested exception is java.lang.NullPointerException
public class Controller {
private List<String> cssFiles;
private List<String> jsFiles;
public Controller () {
this.addCss("global.css");
this.addJs("global.js");
}
public ModelAndView render (ModelAndView model) {
//add Js & Css files
model.addObject("cssFiles", this.cssFiles);
model.addObject("jsFiles", this.jsFiles);
return model;
}
/*
* Add a css file to the page
*/
public final void addCss (String cssPath) {
cssFiles.add(this.cssFiles.size(), cssPath);
}
/*
* Add a javascript file to the page
*/
public final void addJs (String jsPath) {
jsFiles.add(this.jsFiles.size(), jsPath);
}
}
答案 0 :(得分:3)
cssFiles
和jsFiles
从未明确初始化,因此为空。您应该使用List
实施初始化它们,例如ArrayList
。
private List<String> cssFiles = new ArrayList<String>();
private List<String> jsFiles = new ArrayList<String>();
声明字段(类变量)并且不指定它时,值默认为null(对于引用),0(对于数字)或false(布尔值)。
答案 1 :(得分:0)
public Controller () {
this.cssFiles = new ArrayList<String>();
this.jsFiles = new ArrayList<String>();
this.addCss("global.css");
this.addJs("global.js");
}
为什么这样做:
public final void addCss (String cssPath) {
cssFiles.add(this.cssFiles.size(), cssPath);
}
public final void addJs (String jsPath) {
jsFiles.add(this.jsFiles.size(), jsPath);
}
真的不需要第一个论点......