Results 1 to 2 of 2

Thread: complex constructor form data binding

  1. #1
    Join Date
    Jan 2011
    Posts
    10

    Default complex constructor form data binding

    Hi.

    I am wondering is there way to bind objects with complex constructor.

    If i have som object e.g

    Code:
    public class MyObject1
    {
           private Long _id;
           private String _name;
    
           public void setName(String name)
           {
                _name = name;
            }
            public String getName(String name)
           {
                return _name;
            }
    
             // .... here goes remaining setters and getters methods.
    }
    So if i send form data and then use in my controller annotation @ModelAttribute

    Code:
    public ModelAndView myController(@ModelAttribute("myObject1") MyObject1 myObject1
    {
     // ... here goes remaining controller code
    }
    This situation works.

    But if my object is like this

    Code:
    public class MyObject2
    {
           private final String _property;
    
           public MyObject2(String property)
           {
                 _property = property;
           }
    
           private Long _id;
           private String _name;
    
           public void setName(String name)
           {
                _name = name;
            }
            public String getName(String name)
           {
                return _name;
            }
    
             // .... here goes remaining setters and getters methods.
    }
    Now i don't have simple construcor. So i can't create object like this :
    Code:
     MyObject2 xxx= new MyObject2();
    i have to use :
    Code:
    MyObject2 yyy= new MyObject2("some property");
    So when i'm binding form data to this new object i'm getting these exception:

    Code:
    org.springframework.beans.InvalidPropertyException: Invalid property ....
               Could not instantiate property type [com.myPackage.MyObject2] to auto-grow nested property path: java.lang.InstantiationException
    is there way to resolve this?

    thanks.

  2. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,632

    Default

    Create a method which constructs your object and annotate it with @ModelAttribute or create a method which reacts to a GET request, constructs the object, put it in the model and make it a @SessionAttribute. Spring cannot use the auto instantiation feature so you will have to do the work yourself.
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •