0

我无法在下面的课程中摆脱这个 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);
    }
}
4

2 回答 2

3

cssFiles并且jsFiles从未显式初始化,因此为空。您应该使用List诸如ArrayList.

private List<String> cssFiles = new ArrayList<String>();
private List<String> jsFiles = new ArrayList<String>();

当您声明一个字段(类变量)并且不分配它时,该值默认为 null(对于引用)、0(对于数字)或 false(布尔值)。

于 2012-04-27T00:24:00.290 回答
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);
}

真的不需要第一个参数...

于 2012-04-27T00:29:47.220 回答