JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy
  • Contact Us

Spring 4.2 Released

July 31, 2015 by Krishna Srinivasan Leave a Comment

Spring IO community has announced its release of Spring Framework 4.2. There is no great or major features added as part of this release. This release is mainly for refining the existing features and minor new features. The following are the list of new features added as part of this release.
image

In our earlier articles we have written about the Spring 5 and roadmap for the future releases. We can consider that this release will be the final change in the 4.x release cycle.

We have a cover story of Spring 4 and any features released under Spring 4 Tutorials. This would be helpful to understand the road map of Spring 4 related changes.

This post is just a summary of the features introduced in the release. Stay tuned for more details about this release features.

  1. Annotation detection on Java 8 default methods (e.g. @Bean)
  2. Annotation-based application events (@EventListener)
  3. First-class support for annotation attribute aliases (@AliasFor)
  4. Full nested path processing for direct field bindingData binding and conversion for JSR-354 Money & Currency
  5. Integration with Hibernate ORM 5.0 (natively and via JPA)
  6. Standards-based bean scripting via JSR-223 (JRuby, JavaScript)
  7. JSR-223 based web views (with a focus on JavaScript on Nashorn)
  8. Rich support for CORS and declarative HTTP caching
  9. First-class support for HTTP Streaming and Server-Sent EventsCompletableFuture for handler methods and @Async methods
  10. Support for Jackson’s @JsonView on STOMP endpoint methods
  11. A STOMP client for use over TCP and WebSocket channels
  12. MockMvc HtmlUnit integration for easy local testing of web pages
  13. Integration tests can alternatively be executed with JUnit rules

They are going to release the Spring 4.2 based Spring Boot version. The next feature release of Spring 4.3 will be released on March 2016. These are just incremental features to the Spring 4.x version and there wont be any major / drastic changes to the Spring Framework.

Are you looking for Spring Tutorials, please read our collection of Spring Framework Tutorials.

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials

Spring 4 REST Example

March 20, 2014 by Krishna Srinivasan Leave a Comment

This tutorial provides a simple example for writing the Spring MVC REST services using the Spring 4 APIs. We have written several articles about the spring 4 features in our previous articles. The REST implementation on Spriing 4 also very much similiar to the previous releases. Here I have provided the sample source code what I have used to implement the REST services. If you have any questions, please write it in the comments section.

Also Read:

  • Spring 4 Features
  • RestController in Spring 4

SpringMVC4HelloWorld.java

[code lang=”java”]
package javabeat.net.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/springmvc4")
public class SpringMVC4HelloWorld {

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello(ModelMap model) {
model.addAttribute("msg", "JavaBeat Hello World!");
return "helloWorld";
}

@RequestMapping(value = "/greetings/{msg}", method = RequestMethod.GET)
public String greetingsMsg(@PathVariable String msg, ModelMap model) {
model.addAttribute("msg", msg);
return "helloWorld";
}

}
[/code]

helloWorld.jsp

[code lang=”xml”]
<html>
<body>
<h1>Spring MVC 4.0 REST Example</h1>

<h3>Your Message : ${msg}</h3>
</body>
</html>
[/code]

web.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Spring MVC 4.0 Web Application</display-name>
<servlet>
<servlet-name>spring4-mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>spring4-mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
[/code]

spring4-mvc-dispatcher-servlet.xml

[code lang=”xml”]
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="javabeat.net.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

</beans>
[/code]

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials

Spring 4 Tutorial

December 21, 2013 by Krishna Srinivasan Leave a Comment

This page is regularly updated with the latest information about the Spring 4 framework. It is the most recent stable release for the production applications. Please bookmark this page to have up-to-date information on Spring Framework 4.0 happenings. If you want to add Spring 4 related links or information here, please send to krishnas at javabeat.net.

Spring 3 released on 2009. After a long time, a major release Spring 4 is from Spring community. In this time, there is lot of changes in the spring community. Spring is not just seen as the framework, it is moving beyond that level and seen as a enterprise solution provider.

Get 50% Off the Upcoming REST With Spring Classes over on Baeldung.

Spring is largest Java community in the world. After the acquisition by VMWare, Vmware and EMC has joined and started a initiative called Pivotal.  Spring is integrated with the Pivotal team and providing all the Java solutions needed for the Pivotal customers. By looking at the new projects and road map of Spring, it is exciting to see them in the future.

A comprehensive coverage on Spring is updated at Spring Tutorial.

The purpose of this tutorial is to organize all the posts published on Spring 4 and the recent releases after the main release of Spring 4. It is a one stop location where you can find everything about the spring 4. This page will be updated with the latest new and announcement about the Spring 4 framework.

Spring 4 Tutorials and Examples

Spring Modules

Spring framework consists of more than 20 modules grouped together. These are largely categorized as Core Container, Data Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation, and Test. These are very well depicted in the below diagram.

Spring Architecture

( Image Source )

Spring 4 Releases

Latest : The current version is Spring 4.2.5. The next planned release is Spring 4.3.0 which is scheduled to be released on March 2016.

  • New Features in Spring 4.0 (Preview) : Early announcement for the new version on spring framework. It highlights the expected new features to be introduced.
  • Spring 4.0 Release Candidate (RC1) Announcement : Release candidate 1 announcement
  • Spring 4.0 Release and Features : Much awaited announcement of final release for Spring 4.0 Framework availability to the general public.
  • Spring 4.1 Release Announced : New features added are omprehensive web resource handling, Caching support revisited, JMS support overhaul and Performance improvements.
  • Spring 4.2 Released : This is another feature release with minor features and enhancements added to the existing features. Some of the notable features are Integration with Hibernate ORM 5.0, Annotation Based application events, bean scripting, @JsonView on STOMP endpoint methods and many other features.
  • Spring 4.2.5 Released : It is a maintenance release lots of bug fixes and minor improvements to the spring framework. It provides more stability to the Spring 4 series.
  • Spring 4.3 RC1 Released : This is the final release on spring 4 series. The next release will be spring 5.

Spring 4 Features

  • Spring 4.0 Environment Setup : This tutorials explains the list of dependencies and configurations required for running the Spring 4 applications.
  • Conditional Annotation in Spring 4 : Conditional Annotation Indicates that a component is only eligible for registration when all specified conditions match. The primary objective is to create the bean only after the set of conditions are met.
  • RestController in Spring 4 : One of the API improvements is new @RestController annotation which is inherited from the @Controller annotation. Prior to the version 4.0, all the Spring MVC components has to use the common @Controller annotation to mark that as the controller servlet.
  • Spring 4 – Generics Type as Qualifier : One of the improvements introduces in Spring 4 is the generic types as a form of qualifier when injecting Beans. We have several types of methods to determine the closely matching types for the @Autowired annotation. With the Spring 4 release, you can inject the beans using the narrowing of generic types.

  • @ControllerAdvice : With the release of Spring 4.0, one of the feature is improvements over the existing @ControllerAdvice annotation. You can narrow the scope of the exception handler. For example, you can declare a exception handler which will handle only the exception thrown by the @RestController , a special type of controller introduced in the Spring 4.0.
  • @Profile Annotation : This tutorial explain how to enable profiles in your spring application for different environments. Also this tutorial explains the new improvements in the Spring 4.0 release and how it is different from the older releases.
  • Removed Deprecated Packages and Methods : There are lot of deprecated classes and methods from the previous release 3.2.4 has been completely removed in the Spring 4 release. You can find the list of APIs that has been either removed, added and changed in the Spring 3.2.4 to Spring 4.0.0 API differences report.
  • Java 8 Support : On March 27, 2014, the Spring community was happy to announce the Spring Framework 4.0.3. The reason why is that it was the first release of the Spring Framework with Java 8 support. You can read some of the Java 8 features are used in the Spring API. One more thing is that Java 6 become the minimum requirement to run the Spring 4 applications.

Spring 4.1 Features

  • With the release of Spring 4.1, there is another type of message converter added for Gson library. GSON is another popular JSON parser used similar way how Jackson is used for JSON parsing. This new message converter is implemented as GsonHttpMessageConverter.
    • HttpMessageConverter are used for Marshall and Unmarshall Java objects to and from JSON, XML, etc – over HTTP. Generally there are third part libraries available in the community to use for the purpose. Spring has the beauty of identifying the relavent JAR files in the classpath and use for the JSON / XML conversions.
    • For this purpose, Spring has in-built HttpMessageConverters for parsing the JSON using Jackson (MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath) and MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath). – Read more about HttpMessageConverters.

Spring 4.2 Features

  • @EventListener in Spring 4.2 : This tutorial highlights the advantage of using @EventListener in Spring 4.2 for listening to the events. Annotation driven event listener is a new feature introduced in Spring 4.2 version.
  • Another good improvement is the ability to bind event listeners to transaction phase. For example, if the transactions are in  complete status then that particular event will be triggered. This gives you more flexibility for configuring the events based on transaction status. For that a special type of event listener @TransactionalEventListener is added to spring 4.2. This has exposure to TransactionalPhase which tells spring about when a event has to be fired.
  • Better Application Events : Application events are available since the very beginning of the Spring framework as a mean for loosely coupled components to exchange information. One of the most well known usage of application events is the following
  • Modern Java Component Design with Spring Framework 4.2 (PDF Presentation by Juergen, Spring Framework Lead)
  • Hibernate, Jackson, Jetty etc support in Spring 4.2 : Spring is well-known to actively support the latest versions of common open source projects out there, e.g. Hibernate and Jackson but also common server engines such as Tomcat and Jetty.

Spring 4.3 – Updates

Spring 4.3 is scheduled to be released on Q2 2016. This will be a final major release on Spring 4 series. The following are the list of features that are planned for Spring 4.3. The planning for this release is in early stage, we may gate more updates in the future. We will update the details in the post regularly.

    • Spring 4.3 will still be designed for the general Spring 4 system requirements (Java 6+, Servlet 2.5+)
    • Also getting prepared for an extended 4.3.x support life until 2019, in particular for users on JDK 6 and 7 but also for applications deployed to older app servers on JDK 8.
    • Most important 4.3 plan is to selectively upgrade the third-party dependency libraries: e.g. fully embracing JUnit 4.12, the Jackson 2.5+ APIs, the new JasperReports Exporter API, etc. in order to make Spring’s corresponding integration classes forward-compatible with future generations of those libraries (through avoiding the use of deprecated types and methods).
    • Also fine tune the latest features in Spring framework.

Spring MVC

There are lot of new features introduced as part of the web application development.

    • Spring 4 REST Example : This tutorial provides a simple example for writing the Spring MVC REST services using the Spring 4 APIs. We have written several articles about the spring 4 features in our previous articles. The REST implementation on Spriing 4 also very much similiar to the previous releases. Here I have provided the sample source code what I have used to implement the REST services.

Spring 4 Books

This section gives you more details on most popular books available in the market for Spring 4 release. If you find any good book or resource for preparing Spring 4, please send me a mail at krishnas at javabeat.net. I will add the details in this post. You can also read our list of Spring Framework Books for a quick reference.

  • Spring in Action : Fourth Edition : Spring in Action is the most popular and friendly book for the developers. But, it may not be most suitable for the beginners who are first time learning Spring framework, but it is one of the must have book for spring developers who are working in the real time Spring projects. BUY : Flipkart (India) / Amazon (USA)

Spring 4 Migration

If you ask any developer what is their painful task or challenges in working with a technology, it is obviously adopting latest changes to the technology and migrating their project from older version to the newer one without any issues. Spring developers also faces lot of challenges while migrating from Spring 3.2 to Spring 4.0.

Note that the 3.0.x and 3.1.x lines have been retired already, with no support whatsoever available anymore

  • Spring team have published an extensive tutorial about the migration from Spring 3.2 to Spring 4.0.
  • This slideshare also would be helpful.

Other Topics

Spring 4 Adoption : There is a nice survey published by Baeldund on Spring 4 Adoption. It is clearly shows that most of the projects are already migrated to the latest release of the Spring framework.

Spring 4 Survey

( Source )

Spring Articles Collection Links

  • List of Spring 4 Tutorials and Guides

References

  • Spring Official Documentation 
  • Spring Framework Project Page
  • Spring Framework API

Filed Under: Spring Framework, Tutorials Tagged With: Spring 4 Tutorials

Spring Framework 4.0 Release and Features

December 13, 2013 by Krishna Srinivasan Leave a Comment

It is finally here!!. On 12-December-2013, Spring IO has officially announced that Spring Framework 4.0 GA is available for the production use. Why there is lot of things to talk about Spring 4.0?. It is the major release after Spring 3.0 which has been released on 2009. Also Spring team has transformed to Spring IO with looking beyond just a Java framework, their road maps and projects are not just only for the Java developers, it is more a complete enterprise solution.

Coming back to the release of Spring 4.0, there is plenty of major changes introduced in this release. Here I summarize the prominent features.

Spring 4.0 New Features

1. Deprecated Methods and Packages 

With this new release, all the deprecated methods and packages are dropped and no more supported. This should be the challenging point for those who want to migrate their old spring applications to the new version. As a caution, if you are running the old spring application, then first thing to get rid of your deprecated APIs before migrating to the latest version.

Look at API Differences to know what is changed in new release.

2. Java 8 Support

This is the first version supports all the features of Java 8. Spring team proudly announces that they have fixed all the issues with the Java 8 compatibility and it is ready to use with Java 8 once Open JDK 8 is released on March 2014. Also another update is that, Spring 4.0 has increased the minimum recommendation to Java 6.0. Also it states that any new project recommended to use the Java 7.0 for their projects with Spring 4.0. It still supports the lower version Java 6 and 7 without any problem.

3. Java EE 6 and 7

Java EE 6 or above is now considered the baseline for Spring Framework 4, with the JPA 2.0 and Servlet 3.0 specifications being of most suitable. It is possible to run your application in Servlet 2.5, but it is recommended to use Servlet 3.0 environment.

4.Groovy Bean Definition DSL

It is possible to define Spring beans using Groovy DSL. We can use bean definitions at the bootstrap using Groovy. Read this API to get more details.

5. Spring Core Changes

There are lot of changes to the Spring’s core container.

  • The @Description annotation has been added for developers using Java-based configuration.
  • @Conditional is introduced to conditionally filtering the beans.
  • Beans can now be Ordered when they are autowired into lists and arrays. Both the @Ordered annotation and Ordered interface are supported.
  • If you are using Spring’s annotation support, you can now write custom annotations that expose specific attributes from the source annotation.

There are much more improvements, I will continue writing in this blog about the new features.

6. Spring Web Module Features

  • Most recommended is Servlet 3.0+ environment. If you are using Spring Testing Framework, then Servlet 3.0 compatible JAR is should be in your test classpath.
  • There is new @RestController annotation for defining the REST web services. This has the built-in @ResponseBody attribute. This is a specialized version of @Controller.
  • Spring provides comprehensive timezone support when developing Spring MVC applications.

7. Testing Features

There are several new features introduced for unit testing and integration testing.

  • Almost all the annotations in the spring-test module can now be used as meta-annotations to create custom composed annotations and reduce configuration duplication across tests.
  •  org.springframework.mock.web package is compatible with Servlet 3.0 .

The above features are only the few of them, I will come up with detailed tutorials on each features. Please subscribe here.

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials, Spring Release

@ControllerAdvice Improvements in Spring 4.0

November 22, 2013 by Krishna Srinivasan Leave a Comment

In my earlier article I have explained about the usage of @ControllerAdvice which is introduced from the Spring 3.2 release. It is special type of @Component to declare the global exceptions handler. When you create a class with @ControllerAdvice and then write few methods with the @ExceptionHandler annotations, any exception thrown in the application will be handled by this class. It is acting as the global exception handler. However, you can not restrict this handling to any specific type of controller or classes.

With the release of Spring 4.0, one of the feature is improvements over the existing @ControllerAdvice annotation. You can narrow the scope of the exception handler. For example, you can declare a exception handler which will handle only the exception thrown by the @RestController , a special type of controller introduced in the Spring 4.0.

Setup Spring 4.0 Environment

Here I am using the same example which I have used for the @ControllerAdvice. If you compare both the posts, you would notice the difference in this tutorial.

1. Create Common Controller

[code lang=”java”]
package javabeat.net.exception;

import java.sql.SQLException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ExceptionHandlingCommonController {

@RequestMapping(value = "/sqlexceptionexample")
@ResponseBody
public String getResultSql() throws SQLException {
boolean flag = true;
if (flag) {
throw new SQLException();
}
return "view";
}

}

[/code]

2. Create RestConroller

[code lang=”java”]
package javabeat.net.exception;

import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExceptionHandlingRestController {

@RequestMapping(value = "/exceptionexample")
public String getResult() throws IOException {
boolean flag = true;
System.out.println("Inside Exception");
if (flag) {
throw new IOException();
}
return "view";
}
}
[/code]

3. @ControllerAdvice for RestController

If you look at the below code, this exception handler called only when the exception is thrown from the RestController.

[code lang=”java”]
package javabeat.net.exception;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

@ControllerAdvice(annotations=RestController.class)
public class ExceptionControllerAdvice {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> getSQLError(Exception exception){
HttpHeaders headers = new HttpHeaders();
headers.set("HeaderKey","HeaderDetails");
return new ResponseEntity<String>("Rest Controller Advice Example",headers,HttpStatus.ACCEPTED);
}
}
[/code]

4. Spring Configuration File

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="javabeat.net.exception" />

<mvc:annotation-driven content-negotiation-manager="contentManager"/>
<bean id="contentManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="true"/>
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="text/html" />
<property name="useJaf" value="false"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="html" value="text/html" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>
[/code]

If you have any issues while running this example, please post it in the comments section.

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials

Spring 4.0 Environment Setup

November 22, 2013 by Krishna Srinivasan Leave a Comment

This tutorial explains how to setup your environment for working with the Spring 4.0 examples. Instead of explaining this process in every article, I would write it here so that this tutorial will be linked from the all Spring 4.0 tutorials for the setup reference.

Spring 4.0 Maven Dependency

At this time of writing this tutorial, Spring 4.0 RC1 is released and final version is to be released in the month of December 2013. If you want to get the Release Candidate 1, use the following maven dependency to download the files.

[code lang=”xml”]
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.0.RC1</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>http://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
[/code]

Download Spring 4.0 Library Files

If you are looking to download the JAR files required to run the Spring 4.0 examples, please download it from here:

  • Spring 4.0 RC1 Distribution Download (22-Novmber-2013)

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials

RestController Annotation in Spring 4

November 21, 2013 by Krishna Srinivasan Leave a Comment

In this tutorial I am going to explain one of the new spring annotation @RestController introduced as part Spring 4 release. The spring 4 version comes up with lot of exciting new features. One of the API improvements is new RestController annotation which is inherited from the @Controller annotation.

If you are interested in receiving more updates related to spring framework, spring boot, etc. please subscribe here.

RestController Annotation in Spring 4

RestController in Spring 4

Prior to the version 4.0, all the Spring MVC components has to use the common @Controller annotation to mark that as the controller servlet. When you implement a RESTful web services, the response would be always sent with the response body. To make this simple, Spring 4.0 has provided a specialized version of controller. Look at the definition of the @RestController implementation.

[code lang=”java”]
@Target(value=TYPE)
@Retention(value=RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController[/code]

Spring docs says:

A convenience annotation that is itself annotated with @Controller and @ResponseBody. Types that carry this annotation are treated as controllers where @RequestMapping methods assume @ResponseBody semantics by default.

@ResponseBody – As of version 4.0 this annotation can also be added on the type level in which case is inherited and does not need to be added on the method level.

This tutorial explains with a simple example on how to use the annotation @RestController. I am using the same example of Content Negotiation in Spring MVC 3.2. If you compare both the examples, you would notice the difference.

RestController Example

Here is the example code for RestController annotation.

  • Also Read : REST API Best Practices

UserDetails.java

[code lang=”java”]package javabeat.net.rest;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class UserDetails {
private String userName;
private String emailId;

@XmlAttribute
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}

@XmlAttribute
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
}[/code]

SpringRestControllerDemo.java

[code lang=”java”]package javabeat.net.rest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringRestControllerDemo {
@Autowired UserDetails userDetails;
@RequestMapping(value="/springcontent",
method=RequestMethod.GET,produces={"application/xml", "application/json"})
@ResponseStatus(HttpStatus.OK)
public UserDetails getUser() {
UserDetails userDetails = new UserDetails();
userDetails.setUserName("Krishna");
userDetails.setEmailId("krishna@gmail.com");
return userDetails;
}

@RequestMapping(value="/springcontent.htm", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public String getUserHtml() {
//Test HTML view
return "example";
}
}[/code]

dispatcher-servlet.xml

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="javabeat.net.rest" />

<bean id="userDetails" class="javabeat.net.rest.UserDetails"/>
<mvc:annotation-driven content-negotiation-manager="contentManager"/>
<bean id="contentManager"
class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<property name="favorPathExtension" value="true"/>
<property name="ignoreAcceptHeader" value="true" />
<property name="defaultContentType" value="text/html" />
<property name="useJaf" value="false"/>
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="html" value="text/html" />
<entry key="xml" value="application/xml" />
</map>
</property>
</bean>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

</beans>[/code]

With this new feature, we can use this specialized controller instead using the generic @Controller for the REST services.

Summary

In this tutorial I have explained the use of RestController annotation in spring mvc application. I have used the XML configurations for writing this example.

If you have any questions on using RestController, please drop your comments.

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials, Spring REST

Spring Framework 4.0 RC1 Released

November 5, 2013 by Krishna Srinivasan Leave a Comment

Spring Framework 4.0 Release Candidate 1 is released by Spring IO this week. Earlier they have announced that Spring 4.0 is due to the release in October 2014. However, in the latest blog post they have indicated that it will be available by December 2014. The last addition of new features with this release candidate also included by them in this blog post. The documentation for the upcoming release is not yet reflecting the new version. It looks like we have to wait for the final release. Couple of weeks back, they have given the overview of the new features included in the Spring 4.0. Lets look at the list of new features added for this release candidate. This will be the final addition of the new features and this list will be moved to the final release.

  1. One of the most important theme for this (Spring 4.0) release is the compatibility of JDK 8.0, an upcoming Java version. With this release candidate, Spring framework offers out of the box support for the JDK 8.0 build.
  2. Support for the groovy based bean definitions.
  3. Auto wiring of spring beans using Generic types.
  4. using Objenesis to create CGLIB proxy instances (allowing for constructor injection).
  5. Support for JSR-223. It is scripting support for the Java platform. In the upcoming releases, Java platform will start adding support to the scripting languages out of the box.
  6. Time zone support in Spring MVC.
  7. More configuration options for the Spring MVC’s @ControllerAdvice.
  8. New API MvcUriComponentsBuilder is introduced with this release. It is keeping in mind with the release of Spring HATEOAS.
  9. Lot of fine tuning to the Spring’s Web Socket support.

It is the perfect time to start using the latest build. It is obvious that when release candidates are released, the build quality will be with good quality like in the production release. If you are an early adopter, lets jump start learning the latest version of spring framework.

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials, Spring Release

Conditional Annotation in Spring 4.0

October 2, 2013 by Manisha Patil Leave a Comment

In this article I shall throw some light on one of the new features of Spring 4, Conditional Annotation Type. In the earlier versions of Spring you could handle conditions as below:

  • In Spring with versions earlier to 3.1, you had to use Spring Expression Language (SPeL).
  • With Spring 3.1, a new feature called profiles was introduced which helped us to handle conditions.

Let us see each of these approaches and then understand the Conditional Annotation type in Spring 4.

Spring Expression Language (SPeL)

The SPeL has a Ternary Operator (If-Then-Else) which can be used as conditional statement in your configuration file (spring.xml) as in the example below:

[java]
<bean id="flag">
<constructor-arg value="#{systemProperties[‘system.propery.flag’] ?: false }" />
</bean>
<bean id="bean">
<property name="property" value="#{ flag ? ‘yes’ : ‘no’ }"/>
</bean>
[/java]

I have Spring bean (MyBean) whose value depends on the value of a property (property). MyBean is set dynamically based on environment it runs.

Using Profiles

The second approach as mentioned would be to use of profiles which got introduced since Spring 3.1.

[java]
<!– default configuration – will be loaded if no profile is specified –>
<!– This will only work if it’s put at the end of the configuration file –>
<!– so no bean definitions after that –>
<beans profile="default">
<import resource="classpath:default.xml" />
</beans>
<!– some other profile –>
<beans profile="otherProfile">
<import resource="classpath:other-profile.xml" />
</beans>
[/java]

Conditional Annotation Type In Spring 4

Now let us understand the Conditional Annotation type. This annotation will be introduced in Spring 4, which is set to release by the end of 2013. However, anyone can download the early access release and try the new features. As the official document defines the conditionals class as “Indicates that a component is is only eligible for registration when all specified conditions match”. The primary objective is to create the bean only after the set of conditions are met.

The declaration of Conditional interface is as below:

[java]
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE, ElementType.METHOD)
public @interface Conditional{
Class <!–?extends Condition–>[] value();
}
[/java]

The @Conditional annotation may be used in any of the following ways:

  1. as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes.
  2. as a meta-annotation, for the purpose of composing custom stereotype annotations.
  3. as a method-level annotation on any @Bean method

If a @Configuration class is marked with @Conditional, all of the @Bean methods and @Import annotations associated with that class will be subject to the conditions.

The condition interface is as follows:

[java]

public interface Condition{
/** Determine if the condition matches.
* @param context the condition context
* @param metadata meta-data of the {@link AnnotationMetadata class} or
* {@link Method method} being checked.
* @return {@code true} if the condition matches and the component can be registered
* or {@code false} to veto registration.
*/
boolean matches(ConditionContext context, AnnotatedTypeMedata metadata);
}

[/java]

Let’s see an example:

[java]

public class SystemPropertyCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return (System.getProperty("flag") != null);
}
}

class SystemPropertyAbsentCondition implements Condition {

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
return (System.getProperty("flag") == null);

}
}

[/java]

Here we have two classes SystemPropertyCondition and SystemPropertyAbsentCondition. Both these classes implement Condition interface. The overridden method returns a boolean value based on the property flag.

Now lets define bean definitions one with positive condition and one that specifies the negative condition as below:

[java]

@Bean
@Conditional(SystemPropertyCondition.class)
public SampleService service1() {
return new SampleServiceImpl1();
}

@Bean
@Conditional(SystemPropertyAbsentCondition.class)
public SampleService service2() {
return new SampleServiceImpl2();
}

[/java]

The Conditional annotation can also be used for modifying the behavior of Spring 3.1 based Profiles itself that I mentioned in above sections. Profiles is internally now based on meta-annotation based Conditional. @Profile annotation has been re factored.

Summary

In this article I have tried to consolidate the Conditional annotation type in Spring 4. Also note that condition annotations are not inherited. If a super class has the Conditional annotation, the sub classes will not have that conditions. If you try few examples listed above, it is easy for you to understand this concept. Hope you liked it.

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials, Spring Framework

Spring 4.0 Features At a Glance

September 30, 2013 by Krishna Srinivasan Leave a Comment

If you remember, Spring 3.0 released nearly four years back. There is no other major release from the Spring Framework, only the incremental release like 3.1, 3.2 and 3.3. Now they are breaking the ice with Spring Framework 4.0 announcement. It is announced that the new version would be released any time between September or October this year.

The previous incremental release was Spring 3.2 which introduced lot of new features like:

  1. Spring MVC Test Framework
  2. Asynchronous MVC processing on Servlet 3.0
  3. custom @Bean definition annotations in @Configuration classes
  4. @Autowired and @Value to be used as meta-annotations
  5. Concurrency refinements across the framework
  6. loading WebApplicationContexts in the TestContext framework
  7. JCache 0.5 (JSR-107)

However, early access libraries are available for the download and can try using the package. But, it is certified for the production only after the official stable release. The entire Java community is eagerly waiting for the next major release from the spring framework. The primary theme for this release is compatibility with Java 8.0 and JEE 7.0 support. Java 8.0 will be release on march 2014.

Update: Spring 4 Released 

  • Spring Framework Tutorials
  • Spring 4 Tutorials

Most of the new features in Spring 4.0 is the bringing Java 8.0 and JEE 7.0 support for the Spring community.

Spring 4.0 Features

  • JSR-335 Lambda expressions
  • JSR-310 Date-Time value types for Spring data binding and formatting.
  • JSR-343 JMS 2.0.
  • JSR-338 JPA 2.1.
  • JSR-349 Bean Validation 1.1.
  • JSR-236 Java EE 7 Enterprise Concurrency support.
  • JSR-356 Spring’s WebSocket endpoint mode.
  • Configuring and implementing Spring style application using Groovy 2. Also they specify that first class support for the Groovy applications.
  • Also spring plans to add the HATEOS (Hypermedia as the Engine of Application State) support for REST APIs.

Earlier Spring 4.0 is scheduled for the September release, but it is only developer preview in the September. There is not mentioning of the exact date when new version will be available for the production use.  This would be any time in October as stated in their presentations. They continue working on providing the good support for new features in Java 8.0. The delay in the Java 8.0 release is halted their plan for some time.

We will come up with more updates once it is release. Please stay connected with us Subscribe to our social network sites to receive the latest updates.

Filed Under: Spring Framework Tagged With: Spring 4 Tutorials

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved