Spring MVC实例化内部类表单bean属性

时间:2015-09-22 03:12:27

标签: ajax spring-mvc

我发布的数据如下:

cond[startData]:2015-09-22
cond[endDate]:2015-09-23
cond[orderId]:

我的ajax是:

cond={
   startDate: "2015-09-22",
   endDate: "2015-09-23",
   orderId: ""
}
queryData = {cond:cond};
$.ajax({
    url: "orderDetail",
    type: "post",
    dataType:"json",
    data: queryData,
    success: function(data){

    }
});

我的弹簧形式是

public class OrderFormBean {
     private Cond cond;
     private Result result;

     // query condition
     public class Cond {
         private String startDate;
         private String endDate;
         private String orderId;
     }

     // query result
     public class Result {
         private String orderId;
         private String orderDate;
         private String operator;
         ...
     }
     ...
 }

因此,它会导致错误:

org.springframework.beans.NullValueInNestedPathException: Invalid property 'cond' of bean class [*.OrderFormBean]: Could not instantiate property type [*.OrderFormBean$Cond] to auto-grow nested property path: java.lang.InstantiationException: *.OrderFormBean$Cond

修改

我发现即使我以这种方式发布数据:

queryData = {
    "cond.startDate": startDate,
    "cond.endDate": endDate,
    "cond.balanceType": balanceType,
    "cond.orderId": orderId
};

Spring仍会产生错误Could not instantiate property type [*.OrderFormBean$Cond]

如果我将内部类Cond移到外面,那么Spring MVC就可以了。

所以这是内部类的原因,Spring无法实例化它。

根据这个 How to create a Spring Bean of a Inner class?,有一个xml配置。但我不想配置它,因为未配置OrderFormBean

1 个答案:

答案 0 :(得分:1)

您的错误是由字段result为空而引起的。

尝试以下方法:

 cond={
    startDate: "2015-09-22",
    endDate: "2015-09-23",
    orderId: ""
 };

 result={
    /*whatever you are going to write here*/
 };

 queryData = {
    cond: cond,
    result: result
 };

参考:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/NullValueInNestedPathException.html

编辑:

此外,您的内部类无法实例化,因为非静态内部类没有默认(无参数)构造函数

解决方案是:要么将内部类标记为static,要么将它们移到“包含”类之外(转移到它们各自的.java文件中)

有关详细信息,请阅读: http://thecodersbreakfast.net/index.php?post/2011/09/26/Inner-classes-and-the-myth-of-the-default-constructor