Announcement Announcement Module
Collapse
No announcement yet.
complex constructor form data binding Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    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.

    Comment

    Working...
    X