{"id":3897,"date":"2011-12-08T10:19:56","date_gmt":"2011-12-08T09:19:56","guid":{"rendered":"http:\/\/blog.dutchworks.nl\/?p=3897"},"modified":"2011-12-08T10:19:56","modified_gmt":"2011-12-08T09:19:56","slug":"use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver","status":"publish","type":"post","link":"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/","title":{"rendered":"Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver"},"content":{"rendered":"<p>How flexible is Spring MVC in combination with immutable objects? Why don&#8217;t we want Spring MVC decide for us how to build our objects used for binding? Curious how we tackled this problem? Read on!<\/p>\n<p>In our current project we are using Spring MVC 3 to build our frond-end.<br \/>\nThe binding mechanism of Spring MVC is very powerfull and flexible.<br \/>\nFor example Spring MVC will automaticly bind fields from the request to the object you are using in your controller. But binding fields from the request to an object will only work when the class contains getters and setters.<\/p>\n<p>An example<br \/>\nOur straightforward mutable address class:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class MutableAddress {\n\n    private String street;\n    private String houseNumber;\n    private String postalCode;\n    private String city;\n\n    public String getStreet() {\n        return street;\n    }\n\n    public void setStreet(String street) {\n        this.street = street;\n    }\n\n   \/\/ Getters and setters for all other fields\n}\n<\/pre>\n<p>The handler method on the controller takes a MutableAddress object (for example populated with data from the form) and saves it.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@Controller\npublic class AddressController {\n\n   @RequestMapping(value = &quot;\/add&quot;, method = POST)\n   public String storeAddress(MutableAddress mutableAddress) {\n\taddressService.storeAddress(mutableAddress);\n\treturn &quot;redirect:\/overview&quot;;\n   }\n}\n<\/pre>\n<p>This all works fine but in our case we use immutable objects by design. So we don\u2019t have any setters on our address class. The idea behind an immutable object is once it is created it will contain the correct values and cannot be changed anymore. So Spring MVC has some influence on the objects that we are using for binding data, but there is a way we can avoid that.<\/p>\n<p>This is how the immutable version of our address class looks like:<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class ImmutableAddress {\n\n    private final String street;\n    private final String houseNumber;\n    private final String postalCode;\n    private final String city;\n\n    public ImmutableAddress(String street, String houseNumber, String postalCode, String city) {\n        Assert.hasText(street, &quot;'street' must contain text&quot;);\n        Assert.hasText(houseNumber, &quot;'houseNumber' must contain text&quot;);\n        Assert.hasText(postalCode, &quot;'postalCode' must contain text&quot;);\n        Assert.hasText(city, &quot;'city' must contain text&quot;);\n\n        this.street = street;\n        this.houseNumber = houseNumber;\n        this.postalCode = postalCode;\n        this.city = city;\n    }\n\n    public String getStreet() {\n        return street;\n    }\n\n   \/\/ All getters for the other fields. We don\u2019t have setters!\n}\n<\/pre>\n<p>The ImmutableAddress doesn\u2019t contain a default constructor and can only be instantiated by passing in all parameters. Note that all fields are final and again we don\u2019t have any setters! So out of the box using the ImmutableAddress in the method of our controller will not work.<\/p>\n<p>Because we want to use ImmutableAddress directly in our controller method we have to do the binding part ourself. The best way to do this is to write a custom <a title=\"WebArgumentResolver\" href=\"http:\/\/static.springsource.org\/spring\/docs\/3.0.6.RELEASE\/javadoc-api\/org\/springframework\/web\/bind\/support\/WebArgumentResolver.html\" target=\"_blank\" rel=\"noopener\">WebArgumentResolver<\/a>.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\npublic class ImmutableAddressWebArgumentResolver implements WebArgumentResolver {\n\n    @Override\n    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {\n        if (ImmutableAddress.class.equals(methodParameter.getParameterType())) {\n            ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;\n            HttpServletRequest request = servletWebRequest.getRequest();\n\n            String street = request.getParameter(&quot;street&quot;);\n            String houseNumber = request.getParameter(&quot;houseNumber&quot;);\n            String postalCode = request.getParameter(&quot;postalCode&quot;);\n            String city = request.getParameter(&quot;city&quot;);\n            return new ImmutableAddress(street, houseNumber, postalCode, city);\n        }\n\n        return WebArgumentResolver.UNRESOLVED;\n    }\n}\n<\/pre>\n<p>As you can see it\u2019s quite easy. The only thing to do is implement a single method called &#8220;resolveArgument&#8221;. The implementation pulls out the parameters from the request and constructs a new ImmutableAddress that will be returned. This is only done when a ImmutableAddress is used as a parameter in one of our controller methods. In all other cases our custom WebArgumentResolver can\u2019t resolve the arguments for the request so WebArgumentResolver.UNRESOLVED will be returned.<\/p>\n<p>We have only one step left and that is to make sure our custom resolver kicks in before the default one of Spring MVC does.<\/p>\n<p>Define our ImmutableAddressWebArgumentResolver as a Spring bean<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\n&lt;!-- Our custom argumentResolver --&gt;\n    &lt;bean id=&quot;afnameIndentificatieArgumentResolver&quot;\n          class=&quot;nl.dutchworks.blog.web.binding.ImmutableAddressWebArgumentResolver&quot;\/&gt;\n<\/pre>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\n&lt;bean class=&quot;org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter&quot;\n          p:customArgumentResolver-ref=&quot;immutableAddressWebArgumentResolver&quot;&gt;\n&lt;\/bean&gt;\n<\/pre>\n<p>Now we can use the ImmutableAddress directly in our controller<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\n@RequestMapping(value = &quot;\/add-immutable&quot;, method = POST)\npublic String storeAddress(ImmutableAddress mutableAddress) {\n\taddressService.storeAddress(mutableAddress);\n\treturn &quot;redirect:\/overview&quot;;\n}\n<\/pre>\n<p>Make sure you don\u2019t use:<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\n&lt;mvc:annotation-driven \/&gt;\n<\/pre>\n<p>in your Spring context because we configured the AnnotationMethodHandlerAdapter in the context to make use of the customArgumentResolver.<\/p>\n<p>At the moment of writing Spring 3.1 RC1 is available and you are able to use the mvc namespace to register your custom argument resolver:<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\n&lt;mvc:annotation-driven&gt;\n\t&lt;mvc:argument-resolvers&gt;\n\t\t&lt;bean class=&quot;nl.dutchworks.blog.web.binding.ImmutableAddressWebArgumentResolver&quot;\/&gt;\n\t&lt;\/mvc:argument-resolvers&gt;\n&lt;\/mvc:annotation-driven&gt;\n<\/pre>\n<p>My conclusion: there is no need to let Spring MVC decide the way you should build your objects for binding. And you don&#8217;t have to because Spring MVC is flexible enough just use WebArgumentResolvers!<\/p>\n<p>To dive a little bit deeper in the code download the complete example <a href=\"http:\/\/blog.dutchworks.nl\/wp-content\/uploads\/2011\/12\/dw-webargument-resolver-blog.zip\">here<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>How flexible is Spring MVC in combination with immutable objects? Why don&#8217;t we want Spring MVC decide for us how to build our objects used for binding? Curious how we tackled this problem? Read on! In our current project we are using Spring MVC 3 to build our frond-end. The binding mechanism of Spring MVC [&hellip;]<\/p>\n","protected":false},"author":113,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"content-type":"","footnotes":""},"categories":[31,10,94],"tags":[271,11,144],"class_list":["post-3897","post","type-post","status-publish","format-standard","hentry","category-java","category-development","category-spring","tag-immutable-objects","tag-java","tag-spring-mvc"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.4 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver - Trifork Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver - Trifork Blog\" \/>\n<meta property=\"og:description\" content=\"How flexible is Spring MVC in combination with immutable objects? Why don&#8217;t we want Spring MVC decide for us how to build our objects used for binding? Curious how we tackled this problem? Read on! In our current project we are using Spring MVC 3 to build our frond-end. The binding mechanism of Spring MVC [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/\" \/>\n<meta property=\"og:site_name\" content=\"Trifork Blog\" \/>\n<meta property=\"article:published_time\" content=\"2011-12-08T09:19:56+00:00\" \/>\n<meta name=\"author\" content=\"Tim van Baarsen\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Tim van Baarsen\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/\",\"url\":\"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/\",\"name\":\"Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver - Trifork Blog\",\"isPartOf\":{\"@id\":\"https:\/\/trifork.nl\/blog\/#website\"},\"datePublished\":\"2011-12-08T09:19:56+00:00\",\"author\":{\"@id\":\"https:\/\/trifork.nl\/blog\/#\/schema\/person\/f31f695b29e14f666e02899dc311bac1\"},\"breadcrumb\":{\"@id\":\"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/trifork.nl\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/trifork.nl\/blog\/#website\",\"url\":\"https:\/\/trifork.nl\/blog\/\",\"name\":\"Trifork Blog\",\"description\":\"Keep updated on the technical solutions Trifork is working on!\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/trifork.nl\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/trifork.nl\/blog\/#\/schema\/person\/f31f695b29e14f666e02899dc311bac1\",\"name\":\"Tim van Baarsen\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/trifork.nl\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/43f199cc9e2f2a04f9906791d923e96c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/43f199cc9e2f2a04f9906791d923e96c?s=96&d=mm&r=g\",\"caption\":\"Tim van Baarsen\"},\"url\":\"https:\/\/trifork.nl\/blog\/author\/tim\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver - Trifork Blog","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/","og_locale":"en_US","og_type":"article","og_title":"Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver - Trifork Blog","og_description":"How flexible is Spring MVC in combination with immutable objects? Why don&#8217;t we want Spring MVC decide for us how to build our objects used for binding? Curious how we tackled this problem? Read on! In our current project we are using Spring MVC 3 to build our frond-end. The binding mechanism of Spring MVC [&hellip;]","og_url":"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/","og_site_name":"Trifork Blog","article_published_time":"2011-12-08T09:19:56+00:00","author":"Tim van Baarsen","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Tim van Baarsen","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/","url":"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/","name":"Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver - Trifork Blog","isPartOf":{"@id":"https:\/\/trifork.nl\/blog\/#website"},"datePublished":"2011-12-08T09:19:56+00:00","author":{"@id":"https:\/\/trifork.nl\/blog\/#\/schema\/person\/f31f695b29e14f666e02899dc311bac1"},"breadcrumb":{"@id":"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/trifork.nl\/blog\/use-immutable-objects-in-your-spring-mvc-controller-by-implementing-your-own-webargumentresolver\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/trifork.nl\/blog\/"},{"@type":"ListItem","position":2,"name":"Use immutable objects in your Spring MVC controller by implementing your own WebArgumentResolver"}]},{"@type":"WebSite","@id":"https:\/\/trifork.nl\/blog\/#website","url":"https:\/\/trifork.nl\/blog\/","name":"Trifork Blog","description":"Keep updated on the technical solutions Trifork is working on!","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/trifork.nl\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/trifork.nl\/blog\/#\/schema\/person\/f31f695b29e14f666e02899dc311bac1","name":"Tim van Baarsen","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/trifork.nl\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/43f199cc9e2f2a04f9906791d923e96c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/43f199cc9e2f2a04f9906791d923e96c?s=96&d=mm&r=g","caption":"Tim van Baarsen"},"url":"https:\/\/trifork.nl\/blog\/author\/tim\/"}]}},"_links":{"self":[{"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/posts\/3897","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/users\/113"}],"replies":[{"embeddable":true,"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/comments?post=3897"}],"version-history":[{"count":0,"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/posts\/3897\/revisions"}],"wp:attachment":[{"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/media?parent=3897"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/categories?post=3897"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/trifork.nl\/blog\/wp-json\/wp\/v2\/tags?post=3897"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}