【问题标题】:why autowired variable is null?为什么自动装配变量为空?
【发布时间】:2015-12-02 14:07:52
【问题描述】:

我正在使用 spring 框架4。我尝试开发一些服务器程序。所以,我想使用 JUnit 测试控制器类。但是,当我运行测试类时,会发生 NullPionterException。我在这个网站上搜索了几个答案。但我无法修复我的代码。帮帮我。

这是我的控制器类。

package kr.ac.jbnu.sql.soremore.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.jcr.Node;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.IRDMLConverter;
import kr.ac.jbnu.sql.soremore.service.IRDMLDBMgmt;
import kr.ac.jbnu.sql.soremore.service.IRDMLRDFMgmt;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;
import kr.ac.jbnu.sql.soremore.service.RDMLRDFException;
import kr.ac.jbnu.sql.soremore.service.RevisionControlException;
import kr.ac.jbnu.sql.soremore.service.rdf.RDFConverter;

import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.Resource;

// reference
// http://crunchify.com/simplest-spring-mvc-hello-world-example-tutorial-spring-model-view-controller-tips/
@Controller
public class SoremoreController {

    private static final int buffer_size = 1024;
    static Logger logger = Logger.getLogger(SoremoreController.class.getName());
    private static String fileName = "";

    @Autowired
    private ApplicationContext appContext  = null;

    @Autowired
    private IRDMLConverter rdmlConverter  = null;

    @Autowired
    private IRDMLRDFMgmt rdmlRDFMgmt  = null;

    @Autowired
    private IRDMLDBMgmt rdmlDBMgmt = null;

    @Autowired
    private RDFConverter rdfConverter  = null;

    private List<String> remainedBaseWorkProductItemIds;
    private List<String> remainedInputedWorkProductItemIds;
    private List<String> sameIds;

//  @RequestMapping(value = "/storeArtifacts", method = { RequestMethod.GET })
//  @ResponseBody
//  String storeArtifacts(HttpServletRequest request,
//          HttpServletResponse response) {
//
//      String rootPath = System.getProperty("catalina.home");
//      File dir = new File(rootPath + File.separator + "tmpFiles");
//      boolean issuccesful = false;
//      String hwpmlPath = dir.getAbsolutePath() + File.separator + fileName
//              + ".xml";
//
//      return storeRDML(hwpmlPath);
//  }

    public String storeRDML(RDML rdml) {
//  public String storeRDML(String hwpmlPath) {
        boolean issuccesful;
//      System.out.println(hwpmlPath);
//      RDML rdml = null;
        // 1. request to convert XML to RD-ML
//      try {
//          rdml = rdmlConverter.convertHWPMLToRDML(hwpmlPath);
//      } catch (RDMLConversionException e) {
//          e.printStackTrace();
//          return "you failed to convert hwpml to rdml";
//      }

        // 2. request to store RD-ML to Apache Jena
        try {
            issuccesful = storeRDML0(rdml);
        } catch (RDMLRDFException e) {
            e.printStackTrace();
            return "you failed to store rdml";
        } catch (RDMLDBException e) {
            e.printStackTrace();
            return "you failed to store rdml";
        } catch (RevisionControlException e) {
            e.printStackTrace();
            return "you failed to store rdml";
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "you failed to store rdml";
        }

        return "you successfully store rdml";
    }

    // forward request to file converter
    @RequestMapping("/convertHWP")
    public ModelAndView convertHWP() {
        return new ModelAndView("convertHWP");
    }

    @RequestMapping(value = "/queryArtifacts", method = { RequestMethod.GET })
    @ResponseBody
    String queryArtifacts(
            @RequestParam(value = "keyword", required = false) String keyword,
            HttpServletRequest request, HttpServletResponse response)
            throws UnsupportedEncodingException, Exception {
        logger.info("Query Artifacts:" + keyword);

        StringBuilder sb = new StringBuilder();

        try {
            RDML[] results = rdmlRDFMgmt.query(keyword);
            for (RDML rdml : results) {
                sb.append(rdml.getIdFromDocument(rdml.getRdmlAsDocument()))
                        .append(",");
                // retrive rdml documents from Jackrabbit
                // RDML rdmlFromJackRabbit =
                // rdmlDBMgmt.getRDML(rdml.getRdmlID());
                // sb.append(rdmlFromJackRabbit.getRdmlAsString(rdml.getRdmlAsDocument()));
            }
        } catch (RDMLRDFException e1) {
            e1.printStackTrace();
        }

        System.out.println("keyword :" + keyword);

        return "result for " + keyword + ":"
                + sb.toString().substring(0, sb.toString().length() - 1);
    }

    // private String convertArtifactIntoXML(HttpServletRequest request,
    // HttpServletResponse response, String path) {
    // String fileExtension = path.substring(path.lastIndexOf(".")+1);
    //
    // logger.info("convertArtifactIntoXML:"+ path);
    //
    // if( fileExtension.equals(ArtifactTypes.hwp))
    // {
    // // TODO forward request to hwp to xml converter
    // }
    // else
    // {
    // // TODO for processing docx, pptx, xlsx
    // }
    // return "";
    // }

    /**
     * Upload single file using Spring Controller
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public @ResponseBody String uploadFileHandler(
            @RequestParam("name") String name,
            @RequestParam("file") MultipartFile file) {
        File serverFile = null;
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                serverFile = new File(dir.getAbsolutePath() + File.separator
                        + name + ".hwp");
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location="
                        + serverFile.getAbsolutePath());
                fileName = name;
                return "You successfully uploaded file=" + name;
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name
                    + " because the file was empty.";
        }
    }

    /**
     * Upload multiple file using Spring Controller
     */
    @RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)
    public @ResponseBody String uploadMultipleFileHandler(
            @RequestParam("name") String[] names,
            @RequestParam("file") MultipartFile[] files) {

        if (files.length != names.length)
            return "Mandatory information missing";

        String message = "";
        for (int i = 0; i < files.length; i++) {
            MultipartFile file = files[i];
            String name = names[i];
            try {
                byte[] bytes = file.getBytes();

                // Creating the directory to store file
                String rootPath = System.getProperty("catalina.home");
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();

                // Create the file on server
                File serverFile = new File(dir.getAbsolutePath()
                        + File.separator + name);
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();

                logger.info("Server File Location="
                        + serverFile.getAbsolutePath());
                message = message + "You successfully uploaded file=" + name
                        + "<br />";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        }
        return message;
    }

    @RequestMapping("/upload")
    public ModelAndView upload() {
        return new ModelAndView("upload");
    }

    @RequestMapping("/uploadMultifiles")
    public ModelAndView uploadMultipleFile() {
        return new ModelAndView("uploadMultiple");
    }

    @RequestMapping("/queryAndResult")
    public ModelAndView queryAndResult() {
        return new ModelAndView("queryAndResult");
    }

    @RequestMapping("/query")
    public ModelAndView query() {
        return new ModelAndView("query");
    }

    // ////////////////////////////////////
    // String ������ �޽����� ����
    @RequestMapping("/welcome")
    public ModelAndView helloWorld() {
        String message = "<br><div align='center'>"
                + "<h3>********** Hello World, Spring MVC Tutorial</h3>This message is comming from CrunchifyHelloWorld.java **********<br><br>";
        return new ModelAndView("welcome", "message", message);
    }

    public void storeRDMLWithTraceability(RDML rdml, String previousRDMLId,
            TraceabilityTypes satisfy) throws IOException {
        String rdURI = rdfConverter.rdURI;
        String rdmlID = rdml.getRdmlAsDocument().getRootElement()
                .getAttribute("id").getValue();

        Model rdfModel = rdfConverter.createRDFmodelfromRD(rdml
                .getRdmlAsDocument());
        Property traceType = rdfModel.createProperty(rdURI + rdmlID,
                satisfy.satisfy.toString());
        Resource rdfWorkProduct = rdfModel.getResource(rdURI + rdmlID);
        rdfWorkProduct.addProperty(traceType, previousRDMLId);

    }

    public String deleteRDMLTraceability(String previousRDMLId1,
            String previousRDMLId2) {

        return null;
    }

    public String updateRDMLTraceability(String previousRDMLId1,
            String previousRDMLId2, TraceabilityTypes satisfy) {
        return null;
    }

    public ArrayList<RDML> searchRDML(String rdmlKeyWord) {
        return null;
    }

    public RDML getRDML(String rdmlID) {
        // TODO Auto-generated method stub
        return null;
    }

    public ArrayList<String> getParentIDs(String rdmlID) {
        // TODO Auto-generated method stub
        return null;
    }

    public ArrayList<String> getChildIDs(String rdmlID) {
        // TODO Auto-generated method stub
        return null;
    }

    public ArrayList<Traceability> getDirectLinkedTraceability(String rdmlID) {
        // TODO Auto-generated method stub
        return null;
    }

    private boolean storeRDML0(RDML rdml) throws RevisionControlException,
            Exception {
        Node baseWP = null;
        Node inputedWP = null;
        remainedBaseWorkProductItemIds = new LinkedList<String>();
        remainedInputedWorkProductItemIds = new LinkedList<String>();
        sameIds = new LinkedList<String>();
        Document rdmlAsDocument = rdml.getRdmlAsDocument();
        String rdmlId = rdml.getIdFromDocument(rdmlAsDocument);

        RDML curRdml = rdmlDBMgmt.retrieveRecentRDML(rdmlId);
        if (curRdml != null && curRdml.getRdmlAsNode() != null)
            baseWP = curRdml.getRdmlAsNode();
        else
            baseWP = null;
        // version 정보 갱신
        inputedWP = rdmlDBMgmt.convertDocToNode(rdmlAsDocument, rdmlId);
        if (baseWP == null) {
            rdmlDBMgmt.initialVersioning(inputedWP);
            // rdf 정보 추가삽입 요망
        } else {
            remainedBaseWorkProductItemIds = rdmlDBMgmt
                    .setAllBaseWorkProductItemId(baseWP);
            remainedInputedWorkProductItemIds = rdmlDBMgmt
                    .setAllInputWorkProductItemId(inputedWP);
            getSameIds();
            Iterator<String> changeNodes = sameIds.iterator();
            while (changeNodes.hasNext()) {
                String chageNodeId = changeNodes.next();
                rdmlDBMgmt.versionUpNode(
                        rdmlDBMgmt.getNode(baseWP, chageNodeId),
                        rdmlDBMgmt.getNode(inputedWP, chageNodeId));
            }
            rdmlDBMgmt.addNodes(baseWP, inputedWP,
                    remainedInputedWorkProductItemIds, "WorkProductItem");
            rdmlDBMgmt.deleteNodes(baseWP, remainedBaseWorkProductItemIds,
                    "WorkProductItem");
        }
        return true;
    }

    private void getSameIds() {
        Iterator<String> baseIter = remainedBaseWorkProductItemIds.iterator();
        while (baseIter.hasNext()) {
            String baseId = baseIter.next();
            Iterator<String> inputedIter = remainedInputedWorkProductItemIds
                    .iterator();
            for (; inputedIter.hasNext();) {
                String inputedId = inputedIter.next();
                if (baseId.equals(inputedId)) {
                    sameIds.add(baseId);
                    remainedBaseWorkProductItemIds.remove(baseId);
                    remainedInputedWorkProductItemIds.remove(inputedId);
                }
            }
        }
    }
}

这是我的测试课。

package kr.ac.jbnu.sql.soremore.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import kr.ac.jbnu.sql.soremore.model.RDML;
import kr.ac.jbnu.sql.soremore.model.Traceability;
import kr.ac.jbnu.sql.soremore.service.RDMLDBException;

import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = { "classpath:/soremore-servlet.xml" })
//@ContextConfiguration(locations = { "/soremore-servlet.xml" })
public class SoremoreControllerTest {

    @Autowired
    SoremoreController soremoreController = null;

    @Test
    public void storeRDML() {
//      String[] hwpmlPaths = { "resource/sample_rdml/예제 1.xml",
//              "resource/sample_rdml/예제 2.xml",
//              "resource/sample_rdml/예제 3.xml",
//              "resource/sample_rdml/예제 4.xml",
//              "resource/sample_rdml/예제 5.xml",
//              "resource/sample_rdml/예제 6.xml",
//              "resource/sample_rdml/예제 7.xml",
//              "resource/sample_rdml/예제 8.xml",
//              "resource/sample_rdml/예제 9.xml",
//              "resource/sample_rdml/예제 10.xml" };
//
//      for (String hwpmlPath : hwpmlPaths) {
//          soremoreController.storeRDML(hwpmlPath);
//      }

        ArrayList<RDML> rdmls = loadTestRDML();
        boolean isSuccessful = false;
        for (RDML rdml : rdmls) {
            try {
                soremoreController.storeRDML(rdml);
                System.out.println();
                isSuccessful = true;
            } catch (Exception e) {
                e.printStackTrace();
                isSuccessful = false;
            }
        }
        Assert.assertTrue(isSuccessful);
    }

    @Test
    public void storeRDMLWithTraceability() throws IOException {
        List<RDML>rdmls = null ;
        String previousRDMLId = "xxx";

        for (RDML rdml : rdmls) {
            soremoreController.storeRDMLWithTraceability(rdml,
                    previousRDMLId, TraceabilityTypes.satisfy);
        }
    }

    @Test
    public void updateRDMLWithTraceability() {
        String previousRDMLId1 = "xxx";
        String previousRDMLId2 = "xxx";

        String updatedTraceability = soremoreController.updateRDMLTraceability(
                previousRDMLId1, previousRDMLId2, TraceabilityTypes.satisfy);
    }

    @Test
    public void deleteRDMLWithTraceability() {
        String previousRDMLId1 = "xxx";
        String previousRDMLId2 = "xxx";

        String removedTraceability = soremoreController.deleteRDMLTraceability(
                previousRDMLId1, previousRDMLId2);
    }

    @Test
    public void searchRDML() {
        String rdmlKeyWord = "abc";

        ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
        for (RDML rdml : rdmls) {
            System.out.println(rdml);
        }
    }

    @Test
    public void searchRDML0() {
        String rdmlKeyWord = "def";

        ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
        for (RDML rdml : rdmls) {
            System.out.println(rdml);
        }
    }

    @Test
    public void searchRDML1() {
        String rdmlKeyWord = "2차년도계획서";

        ArrayList<RDML> rdmls = soremoreController.searchRDML(rdmlKeyWord);
        for (RDML rdml : rdmls) {
            System.out.println(rdml);
        }
    }

    @Test
    public void getRDML() {
        String rdmlID = "abc";
        RDML rdml = soremoreController.getRDML(rdmlID);
    }

    @Test
    public void getParentIDs() {
        String rdmlID = "abcd";

        ArrayList<String> parentIDs = soremoreController.getParentIDs(rdmlID);

        for (String string : parentIDs) {

        }
    }

    @Test
    public void getChildIDs() {
        String rdmlID = "abcd";

        ArrayList<String> childIDs = soremoreController.getChildIDs(rdmlID);

        for (String string : childIDs) {

        }
    }

    public void getDirectLinkedTraceability() {
        String rdmlID = "abcd";
        ArrayList<Traceability> linkedTraceabilities = soremoreController
                .getDirectLinkedTraceability(rdmlID);

        for (Traceability traceability : linkedTraceabilities) {

        }

    }

    public ArrayList<RDML> loadTestRDML() {
        ArrayList<RDML> rdmls = new ArrayList<RDML>();
        String xmlSource = "resource/sample_rdml";

        File sourceDir = new File(xmlSource);
        File[] sourceFiles = sourceDir.listFiles();
        for (File file : sourceFiles) {
            RDML rdml = new RDML();
            rdml.setRdmlAsDocument(createDocument(file));
            rdmls.add(rdml);
        }

        return rdmls;
    }

    private Document createDocument(File rdmlPathAsFile) {
        SAXBuilder jdomBuilder = new SAXBuilder();
        Document jdomDocument = null;
        try {
            jdomDocument = jdomBuilder.build(rdmlPathAsFile);
        } catch (JDOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jdomDocument;
    }
}

这是我的 spring 配置 xml 文件。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:component-scan base-package="kr.ac.jbnu.sql.soremore" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
        <property name="contentType" value="text/html; charset=UTF-8" />
    </bean>



    <!-- for file upload -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- setting maximum upload size -->
        <property name="maxUploadSize" value="20000000" />

    </bean>
</beans>

【问题讨论】:

  • 您已经提供了将近 600 行代码 - 期望任何人都浏览所有这些是不合理的。请将您的代码缩减为仍然可以演示问题的最小示例。我希望有一个很好的例子,just 包含一个测试和一个带有(比如)String 属性的 bean,以证明正在使用该配置。也不清楚您为什么注释掉大量涉及的注释。
  • @JonSkeet:哦,所以你在回答之前确实会阅读问题,看你的速度我一直认为你不需要阅读问题来回答它:P

标签: java spring junit


【解决方案1】:

测试中的 Autowired 变量将为空,除非 Spring 在运行测试时自动装配它。您的评论行 @RunWith(SpringJUnit4ClassRunner.class) 和 @ContextConfiguration 行实现了这一点。

【讨论】:

  • 我同意你的观点,但不确定你的原因是@Ract 首先评论了配置?
  • 我确定是有原因的(我猜 Spring 可能会抱怨配置)。
  • 嗯,Ract 忽略了背后的问题,创建了另一个问题 :)
  • 嗯....我应该删除评论的行吗?但是当我删除该行时,仍然会出现同样的错误。
  • 您应该取消注释已注释的行(RunWith 和 ContextConfiguration 行之一)。
猜你喜欢
  • 2013-09-28
  • 2018-04-16
  • 1970-01-01
  • 2015-07-19
  • 2021-03-13
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 2012-04-23
相关资源
最近更新 更多