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

@SpringBootApplication Annotation in Spring Boot

March 16, 2016 by Krishna Srinivasan Leave a Comment

@SpringBootApplication Annotation
@SpringBootApplication Annotation

@SpringBootApplication annotation is a convenience annotation introduced from Spring Boot 1.2.0. If you have worked on the earlier spring boot versions, it is common that main class always annotate with the following annotations:

  • @Configuration : This annotation is not specific to the spring boot applications. This annotation tags the class as the source for bean definitions. In short, this annotation is used for defining beans using the Java configuration.
  • @EnableAutoConfiguration : This is a spring boot annotation. This annotation enables the application to add the beans using the classpath definitions.
  • @ComponentScan : This annotation tells the spring to look for other components, configurations and services in the specified path.

The above three annotations have become quite common for all the spring boot application main class. This makes it worthwhile to add @SpringBootApplication as a single annotation that represents all the above three annotations. Here is the definition of this annotation looks in the source code:

[code lang=”java”]
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {
……
[/code]

By looking at the code, you can easily understand that using the above three annotations are equivalent of using a @SpringBootApplication annotation.

However, if you want to customize the @EnableAutoConfiguration or @ComponentScan, then you can use the individual annotations as below.

[code lang=”java”]
@EnableAutoConfiguration(exclude={Book.class})
@ComponentScan({"net.javabeat"})
@Configuration
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
[/code]

The same can be used in the @SpringBootApplication as below:

[code lang=”java”]
@SpringBootApplication(exclude=Book.class,scanBasePackages={"net.javabeat"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
[/code]

The following are the parameters accepted in the @SpringBootApplication annotation:

  • exclude – Exclude the list of classes from the auto configuration.
  • excludeNames – Exclude the list of fully qualified class names from the auto configuration. This parameter added since spring boot 1.3.0.
  • scanBasePackageClasses – Provide the list of classes that has to be applied for the @ComponentScan.
  • scanBasePackages – Provide the list of packages that has to be applied for the @ComponentScan. This parameter added since spring boot 1.3.0.

Filed Under: Spring Framework Tagged With: Spring Boot Annotations

Ultimate Guide for Spring Boot DevTools

March 9, 2016 by Krishna Srinivasan Leave a Comment

The main reason why Spring Boot is developed by Spring community is to simplify the packaging and deploying your spring applications to production. Keeping with that in mind, spring boot assumes all the default values loaded at startup is optimized for the production ready application. For example, caching of Thymeleaf templates are enabled by default which improves the performance in the production. However, these settings must be disabled for the development environment to test the applications effectively when ever you make the changes in the code.

This tutorial walks you through the various features available in the devtools module.

The table of contents for this tutorial:

  1. What is Spring Boot DevTools?
  2. Auto Restart
    1. Exclude Resources
    2. Disable Restart
    3. Watch Additional Paths
  3. Default Properties
  4. Live Reload
  5. Summary
Spring Boot Developer Tools Available Since 1.3.0
Spring Boot Developer Tools Available Since 1.3.0

What is Spring Boot devTools?

Spring Boot 1.3 ships with new module spring-boot-devtools. The primary goal of this module is to improve the development speed by enabling some of the key features that are important during the development phase of your project. This tutorial explains how to use spring boot devtools and different options available as part of the spring boot devtools.

You can include this module to your spring boot application by adding the following maven snippet:

[code lang=”xml”]
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
</dependencies>
[/code]

For Gradle build:

[code]
dependencies {
compile("org.springframework.boot:spring-boot-devtools")
}
[/code]

Once you have added the above dependency to the spring boot application, it will add lot of spring-boot-devtools features.

Auto Restart

Greg L. Turnquist is correct, the real gem from spring boot is coming out. If you are a developer, you are well aware that how much important to auto load the application when there is some changes in the code. It is one of the main feature that lacks spring boot application since it’s inception. But, the devtools features brings the auto restart of the application on any code changes.

If there is any changes to the classpath, the application will automatically restart to effect the new changes. This is quite fast when I have tested in my local system. Spring boot team have managed two classloaders, one is for loading the project specific class files (which changes frequently) and another one is for third party libraries.

For any changes to the project files, spring boot restart a classloader that loads the project specific class files. Since it is not loading the entire application, the speed of the restart is much faster. If you have any experience, please write it in the comments section.

Spring Boot DevTools Auto Restart
Spring Boot DevTools Auto Restart

Exclude Resources

When auto restart is enabled, all the files in the classpath will be monitored for the changes. But, if there is any changes to the static files like templates, css, etc. not require any server restart for loading the resources. To overcome that issue, you can easily exclude the files under certain path from the auto restart option. You could add the resources that you don’t want to load on changes:

[code]
spring.devtools.restart.exclude=/META-INF/resources
[/code]

Disable Restart

Also you can disable the restart option by add the spring.devtools.restart.enabled property to the application.properties file as follows:

[code]
spring.devtools.restart.enabled=false
[/code]

The good thing is that when you set this property, immediately it takes effect and you need not manually stop and start the spring boot application.

Watch Additional Paths

By default, spring boot application performs automatic restart only when the resources under classpath changes. But, if you want to enable the auto restart for the resources outside the classpath, then you can use the following property to  add the additional paths on auto restart.

[code]
spring.devtools.restart.additional-paths=/src
[/code]

Default Properties

Spring boot supports multiple cache libraries for improving the performance. By default template caching is enabled by spring boot for improving the performance. However, this is a counter productive at the development time. Prior to spring boot 1.3.0, developers has to update the application.propertries file for disabling the cache.

Now it is changed. By adding the spring-boot-devtools, the following template caches are disabled by default:

  • spring.thymeleaf.cache=false
  • spring.freemarker.cache=false
  • spring.groovy.template.cache=false
  • spring.velocity.cache=false
  • spring.mustache.cache=false

These configurations are updated in the file DevToolsPropertyDefaultsPostProcessor.java

Live Reload

spring-boot-devtools includes the embeded LiveReload server. Whenever there is any changes to the server, the browser will be trigger for the refresh. You can get the free extension for the live reload here.

If you don’t want to start the LiveReload server on the start up, please add the following entry to the application.properties:

[code]
spring.devtools.livereload.enabled=false
[/code]

Note that you will be able to run only one LiveReload server at a time, if you are running multiple applications in your IDE, the first one will have the LiveReload enabled.

You can see the LiveReload server startup message at the console. If you set the spring.devtools.livereload.enabled property to false, then the server will not be started when spring boot initializes the application.

Spring Boot LiveReload Server
Spring Boot LiveReload Server

 Summary

I hope this tutorial provides good information on what is spring boot devtools, what are the features in the devtools and how to use them. At high level, it is an additional module to the spring application for improving the productivity. Especially, the auto restart feature is very useful at the development time. If you have any questions, please write it in the comment section.

Thank you for reading  my blog!! Happy Reading!!

 

Filed Under: Spring Framework Tagged With: Spring Boot Tutorials

Caching Support in Spring Boot

March 5, 2016 by Krishna Srinivasan Leave a Comment

This tutorial highlights the new features added as part of the spring boot 1.3.0 for caching support. Caching has been supported by spring boot, but there is no auto configuration option for the caching in spring boot until now. The new Spring Boot release 1.3.0 has introduced the following features that makes easier to use the caching within spring boot powered applications:

  1. Auto configuration is supported for the caching.
  2. Spring boot actuator adds caching metrics to the /metrics endpoint.
Caching Support in Spring Boot
Caching Support in Spring Boot

In this tutorial, I have explained the above two new features as part of the caching support in spring boot applications. I have used the same example application used as part of the Spring Data Tutorial and added the caching implementation (ehcache) on top of the same example. The revised implementation of the example application I have uploaded at the end of this tutorial for your download. This tutorial just explains the caching specific pieces. Hope that helps. If you have any questions, please write it in the comments section.

Caching Auto Configuration

Spring Boot Cache Auto Configuration Steps
Spring Boot Cache Auto Configuration Steps

Spring Boot simplifies the configuration of caching implementation with auto-configuration support. If you are not familiar with the word auto-configuration, here is the definition: Auto-configuration in spring boot searches the libraries and configuration files in the classpath and initialize the required dependency beans at the application start up. This eliminates the need for manually configuring the beans to instantiate and ready for the use.

For example: If you have the ehcache.xml in the classpath and you have the ehcache 2.x libraries present, then spring boot will configure the ehcache as the caching implementation for your application by initializing the cache managers for ehcache.

Prior to the auto-configuration, you would require the following lines of code in the spring boot configuration file:

[code lang=”java”]
@SpringBootApplication
@EnableCaching
public class MyBooks {
@Bean
public CacheManager cacheManager() { …}

…
}
[/code]

With Spring Boot 1.3.0, the last step of adding the bean definitions also bean eliminated. The following are the steps to enable ehcache for your application:

  1. Add @EnableCaching annotation in the spring boot configuration class. This annotation is the indicator for enabling the caching mechanism in your application.
  2. Next step is to add the required libraries in the classpath. If you are using the ehcache as the cache implementation, then add the dependency to the POM.xml file.
  3. Next step is to add the configuration file for the cache provider. If you are using the ehcache, the add the ehcache.xml at the root of the classpath.

Spring boot tries to detect the following cache providers in the order given below:

  1. Generic
  2. EhCache 2.x
  3. Hazelcast
  4. Infinispan
  5. JCache (JSR-107)
  6. Redis
  7. Guava
  8. Simple

If the spring boot finds more than once cache provider in the classpath, in that case the cache provider must be explicitly specified. Add the following entries to the application.properties file:

[code]
# Only necessary if more than one provider is present
spring.cache.ehcache.provider=net.sf.ehcache.CacheManager
spring.cache.ehcache.config=classpath:config/another-config.xml
[/code]

Caching Metrics in Spring Boot Actuator

/metrics endpoint exposes the various metrics about the running application. Spring Boot 1.3.0 adds the details about the cache implementation also as part of the /metrics endpoint. The following details are exposed:

  • The current size of the cache (cache.xxx.size)
  • Hit ratio (cache.xxx.hit.ratio)
  • Miss ratio (cache.xxx.miss.ratio)

Note: The cache metrics may be different for each provider. So, you have to check the provider documentation for more details about how the metrics about hit / miss ratios are exposed by the provider. When I have tried the sample application, I could not get the hit / miss ratio for ehcache, it looks there is some issue at present. You can see the size of the cache display in the below screenshot. I will update the tutorial with more details.

Spring Boot Cache - Ehcache
Spring Boot Cache – Ehcache

Example Application

Now we review the example application that supports the auto-configuration for caching and exposes the cache metrics. As I have told, this example is the extension of the Spring Data Tutorial. Refer the spring data tutorial if you want to understand how spring data works.

Here is the updated SpringBootApplication.java. The only update is @EnableCaching annotation.

[code lang=”java”]
@Configuration
@SpringBootApplication
@EnableJpaRepositories
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

}
[/code]

You have to enable caching for the one method. The similar way you can do for other methods. If you are looking for more details about the spring caching abstraction, please read our spring cache tutorial.

[code lang=”java”]
@Cacheable ("books")
public Book findOne(long id);
[/code]

Just add ehcache.xml file in the root of the classpath:

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<diskStore path="java.io.tmpdir" />
<defaultCache maxElementsInMemory="10" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
<cache name="books" maxElementsInMemory="50" eternal="false" overflowToDisk="true" timeToIdleSeconds="0" timeToLiveSeconds="86400" />
</ehcache>
[/code]

The project structure would look like this:

Spring Boot Cache Project Structure
Spring Boot Cache Project Structure

When spring boot initializes the ehcache, you would see the following messages in the console which confirms the initialization of ehcache by the example application.

[code]
Bean ‘org.springframework.cache.annotation.ProxyCachingConfiguration’ of type [class org.springframework.cache.annotation.ProxyCachingConfiguration$$EnhancerBySpringCGLIB$$ce3ea348] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Bean ‘org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration’ of type [class org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration$$EnhancerBySpringCGLIB$$866a36c] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Bean ‘spring.cache.CONFIGURATION_PROPERTIES’ of type [class org.springframework.boot.autoconfigure.cache.CacheProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Bean ‘org.springframework.boot.autoconfigure.cache.CacheManagerCustomizers’ of type [class org.springframework.boot.autoconfigure.cache.CacheManagerCustomizers] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Bean ‘org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration’ of type [class org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration$$EnhancerBySpringCGLIB$$f507a8aa] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Bean ‘ehCacheCacheManager’ of type [class net.sf.ehcache.CacheManager] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
Bean ‘cacheManager’ of type [class org.springframework.cache.ehcache.EhCacheCacheManager] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
cacheAutoConfigurationValidator’ of type [class org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration$CacheManagerValidator] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
[/code]

Download the Source Code

[wpdm_package id=’22582′]

Summary

The above sections explains you the auto configuration of caching in spring boot applications and how to expose the caching metrics using the spring boot actuator. This tutorial primarily focused on the ehcache implementation, I would add the other caching provider details in future. Stay tune to receive more updates on spring boot caching.

Thank you for reading my blog!! Happy Reading and Have fun!!

Filed Under: Spring Framework Tagged With: Spring Boot Tutorials

REST API Best Practices

February 27, 2016 by Krishna Srinivasan Leave a Comment

REST becomes common approach for exposing the services to the outside world.  The reason for the popularity is because of it’s simplicity, easy to use, accessed through HTTP (REST can be accessed via any protocols, but most widely used with HTTP), etc. There is a common misconception that any resources exposed through network is considered as REST, but that is not correct. In this tutorial, I am going to explain you some of the best practices that you have to always remember while you are implementing your own REST API.

REST API Design Best Practices

I would like to hear your experience as a REST API developer. If you have come across any best practices that is not mentioned here, please share with us in the comments section.

  • Also Read : REST vs SOAP

Disclamer: these best practices are what I think is good, based from my past experiences. If you think otherwise, feel free to send me an email so we can have a discussion about it.

REST API Design Best Practices

Here is the list of best practices discussed in this tutorial:

  1. Endpoints as nouns, not verbs
  2. Use plurals
  3. Documentation
  4. Version your API
  5. Paging
  6. Use SSL
  7. HTTP Methods
  8. Effectivelu use HTTP Status Codes

1. Endpoints as Nouns, not Verbs

One of the most common bad practice done by the REST API developers are to use the verbs for naming the REST endpoints. However, that is not a best practice. You must always use nouns instead of using verbs.

Example Scenario:

We have a requirement to expose REST web services for retrieving farmers (agriculturist) details in India. The service also should implement the functionality to retrieve other details like income, crops name, address, etc. which are related to each farmer. Each farmer will have a unique ID assigned to them.

In the similar way, there should be services for exposing the crops details and which farmer has cultivated them.

Best Practice:

Have a single endpoint that represents all the operations. In the below example, we expose only one endpoint /farmers for all the operations like get, add, update, delete. The underlying implementations have different HTTP methods that are routed correctly for the different operations. More details provided in the below section for HTTP methods.

  • /farmers
  • /crops

Not Recommended:

Please avoid using the verbs or operations in the naming convention. It is recommended to represent the operation inside the data format (JSON / XML / RAML) or using the HTTP methods. Don’t use the service end points like below:

  • /getFarmers
  • /updateFarmers
  • /deleteFarmers
  • /getCrops
  • /updateCrops
  • deleteCrops

2. Use Plurals

Use plurals for naming your REST services. This is another hot topic among the REST designers to choose between plural or singular nouns for naming the services.

Best Practice:

  • /farmers
  • /farmers/{farmer_id}
  • /crops
  • /crops/{crop_id}

Not Recommended:

  • /farmer
  • /farmer/{farmer_id}

Note: Though I mention using plural is the good practice, for some reason if you stick to using the singular, then follow the same for all the services. Don’t mix up using plurals and singulars. That is why I am not saying anything as bad practice, I just saying that is not recommended. Please decide yourself which is good for your application.

3. Documentation

Documenting the software implementation is the most common practice. This also applies to the REST API implementation. If you write the useful documentation, it will help other programmers to understand.

  • Also Read : RESTful Web Service using JAX-RS 2.0

The most common way to document REST APIs is to produce documentation that lists the API endpoints, and describes the list of operations allowed on each endpoint. There are plenty of tools that allow you to do this in an automated way.

Here is some of the tools that may help you to document your REST services:

  • DRF Docs
  • Swagger
  • Apiary

Please share your experience on documenting your APIs.

4. Version Your API

Any software will evolve over the period of time. This might require a different version for every major changes to the API. When it comes to the REST API version, it is one of the most debated topic among the REST developers community.

There are two common types of versioning for REST API:

  1. URI Versions
  2. Media Type Versions 

URI Version

A simple example how a URI version would look like:

[code]
http://host/v2/farmers
http://host/v1/farmers
[/code]

The following are the main drawbacks of versioning using URI:

  1. It breaks the existing URIs, all the clients has to update to the new URI
  2. It increases the amount of URI versions to manage, this will increase the HTTP caching size of the client to store multiple versions of URI. By adding more number of duplicate URI would affect the percentage of cache hits and it may slow down the performance of your application.
  3. It is highly inflexible, we can not simply change the single resource or small subset of resources.

Media Type Version

This approach send the version details in the header of each request. When we do change the media type and language of the URI, we will go through content negotiation based on the header. This approach is the most preferred option for the REST API versioning.
Instead sending the generic media types like application/json, these would be versioned.
Example Header Information

[code]
GET /account/5555 HTTP/1.1
Accept: application/vnd.farmers.v1+json

HTTP/1.1 200 OK
Content-Type: application/vnd.farmers.v1+json
[/code]

In the media type versioning approach, client has the option of choosing the which version to request from the server. This approach looks better than URI version approach, but the complexity arise in caching the requests with different version that are passed through the header. In simple words, when client caches based on the URI, it is simple, But, caching with key as media type adds complexity.

5. Paging

Sending across large amount of data through HTTP is not a good idea.This will certainly come as a performance issue because serializing the large JSON objects become expensive. A best practice is to paginate the results instead of sending all the records at once. Provide option to paginate the results using next or previous links.

If you are using the pagination in your application, one of the good way to indicate the navigation link is to use the Link HTTP header option.

This link from GitHub will be useful. Also another useful link for link header usage.

6. Use SSL

SSL is must. You should always implement SSL for your REST API. Your application will be accessed from every part of the world, there is no guarantee that it will be accessed securely. With the increasing number cyber crime incidents, we must secure our application rightfully.

  • Also Read : How to Enable SSL on JBoss Server

Industry standard authentication protocols help reduce the effort of securing your API. Don’t use the basic authentication mechanism. Use either Oauth1.0a or Oauth2 for best security to your services. I would recommend Oauth2 personally for it’s latest features.

If you have any points to share with us, please write it in the comments section.

7. Use HTTP Methods

Mapping operations to HTTP methods is easy when you know the characteristics of all the HTTP methods. One of the previous section in this tutorial I have insisted using the HTTP methods for operations instead of writing the different naming service for each operations. This section primarily deals with behavior of  each HTTP methods.

The following are the two characteristics that has to be determined before using a HTTP method:

  • Safety : A HTTP method is considered as safe when invoking that method does not change the state of the resource. For example, when you are retrieving a data using the GET method, this is safe because this method does not update the data to back end.
  • Idempotent : When you get the same response how many times you invoke the same resource, it is known as idempotent. For example, when you try to update a same data to back end, the response will be same for every request made with same data.

Not all the methods are safe or idempotent. Here is the list of methods that can be used for REST API calls and what are the methods safe and idempotent.

REST Http Methods
REST Http Methods

Here is the quick summary of each method and when to use them:

  • GET : This method is safe and idempotent. It is always used for retrieving the information and doesn’t have any side effects.
  • POST : This method is neither safe nor idempotent. This method is most widely used for creating the resources.
  • PUT : This method is idempotent. That is the reason instead POST one can use this method for updating the resources. Avoid using POST for updating the resources.
  • DELETE : As the name implies, this method is used for deleting the resources. But, this method is not idempotent for all the requests.
  • OPTIONS : This method is not used for any resource manipulation. But, it is useful when client doesn’t know the various methods supported for a resource, using this method client can retrieve the various representation of a resource.
  • HEAD : This method used for querying a resource in the server. It is very similar to GET method, but HEAD has to send request and get the response only in the header. As per HTTP specification, this method should not use body for request and response.

8. Effectively Use HTTP Codes

  • Also Read : List of HTTP Status Codes and Explanation

HTTP defines various status codes for indicating different meaning to the client. Your REST API could effectively use all the available HTTP codes to help the client route the response accordingly. Here is the list of HTTP status codes for your reference:

  • 200 OK – This is response to successful GET, PUT, PATCH or DELETE. This code also be used for a POST that doesn’t result in a creation.
  • 201 Created – This status code is response to a POST that results in a creation.
  • 204 No Content – This is a response to a successful request that won’t be returning a body (like a DELETE request)
  • 304 Not Modified – Use this status code when HTTP caching headers are in play
  • 400 Bad Request – This status code indicates that the request is malformed, such as if the body does not parse
  • 401 Unauthorized – When no or invalid authentication details are provided. Also useful to trigger an auth popup if the API is used from a browser
  • 403 Forbidden – When authentication succeeded but authenticated user doesn’t have access to the resource
  • 404 Not Found – When a non-existent resource is requested
  • 405 Method Not Allowed – When an HTTP method is being requested that isn’t allowed for the authenticated user
  • 410 Gone – This status code indicates that the resource at this end point is no longer available. Useful as a blanket response for old API versions
  • 415 Unsupported Media Type – If incorrect content type was provided as part of the request
  • 422 Unprocessable Entity – Used for validation errors
  • 429 Too Many Requests – When a request is rejected due to rate limiting

Summary

I hope this tutorial is useful for understanding how to design your REST API. There is nothing called best for the universe, that is applicable for API design. Here the best practices are compiled based on my experience and discussion with friends who worked on the REST web services applications.

If you have worked on REST API design extensively and if you feel that this tutorial not making any sense to you :), I am happy to hear your feedback. I would like to keep updating this space with more proven techniques to design the best API for your application.

Happy reading and have fun :). Thank you for visiting my blog.

Filed Under: Spring Framework Tagged With: REST API

Spring Framework 4.2.5 Released

February 26, 2016 by Krishna Srinivasan Leave a Comment

Spring team has released it’s latest release Spring Framework 4.2.5. This release is part of the Spring Framework 4’s maintenance release. There are no major changes or features planned as part of this release. This release focus mainly on fixing the issues and providing more stability to the Spring 4 release.

It is highly recommended to upgrade to this release if you are using any of the 4.x release. This would solve any of the existing issues which your application has with Spring Framework.

Spring Framework 4.2.5

With the above announcement, spring team has also announced the release of Spring Framework 4.3.0.M1. This is next release and final release on 4.x series. Spring Framework 4.3.0 will have lot of new features and improvements. After this release, next stop will be the great Spring Framework 5. As you are aware, Spring 5 would have tons of goodies that is going to excite the Spring community.

Spring Framework Tutorials:

  • Complete Guide for Spring Boot
  • Spring Data JPA Tutorials
  • Spring Framework Books

 

Filed Under: Spring Framework Tagged With: Spring Release

Spring Data Hopper Release

February 19, 2016 by Krishna Srinivasan Leave a Comment

Last week spring data team lead Oliver Gierke has announced that Spring Data‘s next release train Spring Data Release Train Hopper M1 has been released. Spring Data has wide list of sub projects that are managed independently as a separate project. In order to have compatibility of each other, Spring Data team releases all the sub projects releases together as a release train. The name of the release trains are named after some famous scientist. The latest one is Hopper.

Spring Data Hopper Release

The following is the release schedule for Spring Data Release Train Hopper:

  • M1 (Mile Stone 1) – February 12th, 2016
  • RC1 (Release Candidate 1) – March 4th, 2016
  • GA (General Access or Final Release) – March 18th, 2016

The following are the list of sub projects that are part of this release:

  • Spring Data Build 1.8
  • Spring Data Commons 1.12
  • Spring Data JPA 1.10
  • Spring Data MongoDB 1.9
  • Spring Data Neo4j 4.1
  • Spring Data Solr 2.0
  • Spring Data Elasticsearch 1.4
  • Spring Data Couchbase 2.0
  • Spring Data Cassandra 1.4
  • Spring Data Gemfire 1.8
  • Spring Data Redis 1.7
  • Spring Data REST 2.5
  • Spring Data KeyValue 1.1
  • Spring Data Envers 1.0

The major changes coming with this release are:

  • The latest release of Spring Data Solr 2.0 will support the Solr 5.0. This is a major change in this release.
  • Spring Data Envers also will be included in the release train. Spring Data Envers is a extension of Spring Data project to support the hibernate envers. With this release train, initial version of Spring Data Envers 1.0 is added. Previously this project was maintained separately.
  • Upgrade to Querydsl 4.
  • Support for Redis cluster

And there are lots of improvements and enhancements coming to all the above projects. Stay tuned here for getting more updates on Spring Data projects.

Filed Under: Spring Framework

Spring and JSON Example

November 6, 2015 by Krishna Srinivasan Leave a Comment

In this example I am going to explain how to get the JSON result in Spring Framework. One of my previous example about content negotiation talks about the same concept. But, here I want to re-visit the same topic with very simple example. Since Spring 3, we can get the JSON result out of the box without much effort. You just have to add the required libraries and then add the mvc:annotation-driven in the spring configuration file. Rest of the things will be taken care by the spring container.

Let’s look at the example code for this tutorial:

1. Project Dependencies – Maven Configurations

Here is the Maven dependency management file used for this tutorial.

pom.xml

[code lang=”xml”]
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>java</groupId>
<artifactId>SpringWebApp</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<maven-jetty-plugin.version>6.1.14</maven-jetty-plugin.version>
<maven-surefire-plugin.version>2.17</maven-surefire-plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<scope>provided</scope>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.11</version>
</dependency>
</dependencies>
<build>

</build>
</project>
[/code]

2. Model

Employee.java

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

public class Employee {
private int empId;
private String empName;
private String city;
private String country;
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
[/code]

3. Controller

JSONController.java

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

import net.javabeat.model.Employee;

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

@Controller
@RequestMapping("/employee")
public class JSONController {

@RequestMapping(value = "{name}/{city}/{country}", method = RequestMethod.GET)
public @ResponseBody
Employee getShopInJSON(@PathVariable String name,
@PathVariable String city, @PathVariable String country) {
Employee employee = new Employee();
employee.setEmpId(1);
employee.setEmpName(name);
employee.setCity(city);
employee.setCountry(country);
return employee;
}

}
[/code]

4. mvc:annotation-driven

Here is the spring configurations used for this tutorial. This is the bare minimum required to up and running your applications. Note that here important part is the <code>annotation-driven</code> declaration which enables the default content handling for the JSON formats. It will search for the classpath and if it found Jackson library, then JSON will be automatically enabled for all the requests.

  • Also Read : component-scan Vs annotation-config Vs annotation-driven

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="net.javabeat.controller" />
<mvc:annotation-driven />
</beans>
[/code]

5. Web App Configurations

web.xml

[code lang=”xml”]
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Spring Web MVC Application</display-name>

<servlet>
<servlet-name>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>mvc-dispatcher</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

</web-app>
[/code]

6. Project Structure

Here is the project structure used for this tutorial.

Spring JSON Project Structure

7. Spring + JSON Example

When you are running the spring and json example, you will get the following output in your browser.

Spring JSON Example Application

I hope this tutorial I have provided basic idea of integrating JSON results into your spring applications. There are lot of improvements on using the JSON results in the latest Spring 4 releases. If you have any questions, please write it in the comments section.

Filed Under: Spring Framework Tagged With: Spring 3.0

Difference Between Java Singleton and Spring Singleton

November 4, 2015 by Krishna Srinivasan Leave a Comment

One of the common misunderstanding among Spring Framework developers is the difference between Spring Singleton and Java Singleton. Interestingly this turns out to be one of the popular interview questions for spring developers to check the understanding of singleton concepts.

If you are working on Java and Spring technologies, it is quite important to know the clear difference between Java Singleton and Spring Singleton. In this post I will explain the basic difference between both the singleton concepts. If you are not already familiar about the Singleton pattern, please read our tutorial about Java Singleton Pattern.

Java singleton class is per classloader and Spring’s singleton is per application context.

Java Singleton vs Spring Singleton

Java Singleton

Note that there is nothing like pre-defined rules for implementing the singleton classes, but the class should be instantiated only once per classloader. Here is the basic steps for implementing the Java Singleton class.

  • When you say singleton class, there should be only one instance of that class can be created.
  • Constructor of that class has to be made as private to avoid instantiation from external classes.
  • Declare a static variable to store the instance for that class.
  • Declare a method that returns the instance of that class.

With the above basic rules, one can classify Java Singleton implementation into the following categories:

  1. Eager Initialization
  2. Static Block Initialization
  3. Lazy Initialization
  4. Thread Safe Singleton

Eager Initialization

In eager initialization, the singleton instance is created at the time of loading class loading. This is the easiest way to create the singleton instance for your singleton class. But, the main drawback of this approach is that the instance will be created even though it is not used by any of the client application. In this approach, you have to just create instance in the static variable declaration.  This approach doesn’t provide any option for exception handling.

Here is the example for eager initialization of singleton instance:

[code lang=”java”]
public class EagerInitialization {
private static final EagerInitialization instance = new EagerInitialization();
private EagerInitialization(){}
public static EagerInitialization getInstance(){
return instance;
}
}
[/code]

Static Block Initialization

This also falls under the eager initialization, the only difference is that instance creation is completed inside the static initializer block.  This approach doesn’t provide any option for exception handling.

Here is the example for static block initialization of singleton instance:

[code lang=”java”]
public class StaticBlockInitialization {
private static StaticBlockInitialization singletonInstance;
private StaticBlockInitialization(){}
static{
try{
singletonInstance = new StaticBlockInitialization();
}catch(Exception e){
throw new RuntimeException("Exception occured while creating the singleton instance");
}
}
public static StaticBlockInitialization getInstance(){
return singletonInstance;
}
}
[/code]

Lazy Initialization

In this approach, we are creating the instance only after loading the class and first invocation of the instance. This will avoid pre-initializing the instance where you don’t need the instance it is requested by the service.

This approach works fine when this class is executed in the single threaded environment, but this will not work fine in the multi-threaded environment when multiple threads are trying to get the new instance simultaneously (Read : Threading in Java).

Here is the simple example for Java Singleton class using lazy initialization approach:

[code lang=”java”]
public class Main {
public static void main(String args[]) {
Singleton singleton = Singleton.getInstance();
System.out.println("Value 1 : " + singleton.getValue());
singleton.setValue(20);
Singleton singleton2 = Singleton.getInstance();
System.out.println("Value 2: " + singleton2.getValue());
}
}

class Singleton {
private Singleton() {}
private static Singleton singleton;
private int value = 10;
public static Singleton getInstance() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
[/code]

Thread Safe Singleton

This is similar to the above approach except that the method used for creating the singleton instance is synchronized. This approach is the most safest and best solution to implement the singleton instance, but it has the performance issues when multiple threads to trying to access the instance simultaneously.
Here is the example for thread safe singleton instance:

[code lang=”java”]
public class ThreadSafeInstance {
private static ThreadSafeInstance singletonInstance;
private ThreadSafeInstance(){}
public static synchronized ThreadSafeInstance getInstance(){
if(singletonInstance == null){
singletonInstance = new ThreadSafeInstance();
}
return singletonInstance;
}
}
[/code]

Spring Singleton

The scope of the Spring singleton is best described as per container and per bean. If you define a bean for a particular class in a single container, spring container will create only one instance for the class. In spring, singleton is termed as one of the scope for defining the beans. Singleton scope is the default scope for spring beans.

singleton

Here is the example declaration of Spring’s singleton beans:

[code lang=”xml”]
<bean id="bookService" class="com.foo.DefaultBookService"/>
<!– the following is equivalent, though redundant (singleton scope is the default) –>
<bean id="bookService" class="com.foo.DefaultBookService" scope="singleton"/>
[/code]

How Spring Singleton Works?

When you think of singleton instance, the first question pop-up in your mind is the thread safety of your application. Spring’s singleton beans are shared among all the requests when your application is running on the multi-threaded environment. How to ensure that your program is thread-safe?.

It is important to remember that your singleton beans should not store any state information. Because the bean instance created once will be shared across all the threads that are requesting for that spring bean. If you inject an object to spring’s singleton bean, it is wired only once and it never get refreshed. It is ideal to make all the controllers as the singleton beans and value objects as the prototype beans.

If you want your prototype beans to be injected every time, then you have to implement the method injection. Otherwise, there is no way to make your singleton object to re-initiate the prototype beans every time. Please read my tutorial about method injection to understand how to instantiate value objects every time it is requested and inject into the singleton objects.

Look this code snippet:

[code lang=”java”]
@Controller
public class SampleController {
int i = 0;
@Autowired
private ValueObject vo;
}
[/code]

In the above code snippet, ValueObject is declared as prototype bean in the XML configurations. However, this object will be injected only once when first time SampleController instance is created. After that the same object will be used for all the requests. In that case, the variable i and vo, should not maintain any state information, otherwise those will be across all the threads.

For example, when the variable i is incremented by one request is shared to another thread. This will lead to confusion and the application won’t be thread safe. To avoid that, don’t declare any instance variable that stores the state information in singleton beans.

Summary

I hope this post would have provided the basic concepts behind Java singleton and Spring singleton. Java singleton is per classloader and spring singleton is per application context for a bean. Also learns about the different scopes in the spring beans to understand when you have to use the singleton bean in spring.

Filed Under: Spring Framework

MySQL Configurations for Spring Boot Applications

October 16, 2015 by Krishna Srinivasan Leave a Comment

In my previous articles for Spring Data JPA, I have used in-memory databases like H2 for persisting data. But, these in-memory databases can not be used for the production. These are only used for the development environment. In this post I will explain the basic configurations for setting up the MYSQL database for your Spring Data JPA and Spring Boot applications.

Here I am going to use the same example used in my previous tutorials. I am just going to replace the database for the sample application. Note that this tutorial uses Spring Boot for deploying the sample application. If you are not using Spring Boot, this may not be much useful to configure your applications.

MySQL configurations for Spring Boot applications

Here is the required configurations to use MySQL database to your Spring Boot application.

Maven Configurations

In the maven’s pom.xml, you just need to add mysql connector. Once this is added to the classpath, Spring Boot will automatically search for the MySQL configurations and use it.

[code lang=”xml”]
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
[/code]

MySQL Configurations

Next step is to add the MySQL configurations in the application.properties.

[code]
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
[/code]

Database Schema / Data

This is only optional for you. If you want to create the tables and load the data at the start up, you have to create schema-mysql.sql and data.sql. The file name of the schema can be either schema-mysql.sql or schema.sql.
schema-mysql.sql

[code]
drop TABLE IF EXISTS book;
create table book(
id int not null primary key,
name varchar_ignorecase(50) not null,
author varchar_ignorecase(50) not null,
price int,
creation_time datetime);
[/code]

I hope in this tutorial you have understood how to use MySQL configurations for spring boot applications. You can download the complete sample application here:
[wpdm_package id=’22582′]

Filed Under: Spring Framework Tagged With: Spring Boot Tutorials

Using @NamedQuery in Spring Data JPA

October 3, 2015 by Krishna Srinivasan Leave a Comment

In my previous article I have explained about how to use @Query annotation for writing the custom queries for Spring Data JPA applications. In this post, I will explain another type of writing the custom queries using @NamedQuery annotation that is part of the JPA specification.

What is NamedQuery?

  • There are two types of queries in JPA. One is dynamic and another one is static. Named query fall under the second category.
  • Named queries are a way of organizing your static queries in a manner that is more readable, maintainable.
  • The named queries are defined in the single place at entity class itself with each query has its unique name. That is the reason it is known as named query.
  • @NamedQuery annotation can be applied only at the class level.
  • Note that named queries have the global scope (can be accessed throughout the persistence unit), so every query should be uniquely identified even if you define queries for different entities.
  • Let’s say, you have a named query with name findOne for an entity Employee, but if you are trying to write another named query with same name fineOne for another entity User, then you will encounter duplicate named query exception. That is the main reason behind prefix the named query name with entity name so that it is uniquely referred.

There are two annotation used for defining the named queries,

  • If you are defining single query, then use @NamedQuery
  • If you have to define more than one named queries, then use @NamedQueries

spring data jpa namedquery

How to use @NamedQuery?

The following are the steps required to implement named queries in your application.

Define @NamedQuery in Entity Class

First, create named queries in your entity class. All the named queries must be written only in the entity classes, query methods will not have any queries defined at method level.
The example definition would look like this:

[code lang=”java”]
@Entity
@NamedQuery(name="Book.findByPrice",
query="select name,author,price from Book b where b.price=?1")
public class Book implements Serializable{
private static final long serialVersionUID = 1L;
@Id
long id;
@Column(name="name")
String name;
@Column(name="author")
String author;
@Column(name="price")
long price;

//getters and setters
[/code]

Create Repository with Query Method

Second, Create Spring Data Custom Repository and create a query method. The method name and the named query name in entity class must be same. Ensure that you are not using @Query annotation with custom query. Because, @Query always takes precedence than other options.
Here is the sample repository interface for the above named query.

[code lang=”java”]
public interface BookNamedQueryRepositoryExample
extends Repository<Book, Long> {
// Query will be used from Named query defined at Entity class
List<Book> findByPrice(long price);
}
[/code]

When to use NamedQuery?

Named queries are ideal when you have the query that is very less likely would change at run time. Here I would list down the characteristics of the named query, it will help you to arrive at your decision whether you have to go for named query or not.

  • All the named queries are validated at application start-up time and there is no failure at run time.
  • It is easier to maintain since all the queries are stored in single location.
  • HQL and native SQL queries can be used and replaced without code changes (no need to re-compile your code).
  • There is no support for the dynamic queries.
  • We can write the complicated SQL queries and map the results to objects.
  • When we are moving existing application to use Spring Data JPA, then we are not required to move the named queries to methods. You have to just create query methods for each named query and map it.

Source Code Download

This example source code contains many examples of Spring Data JPA and not just for @NamedQuery. This example uses Spring Boot for packaging and deploying spring application.
[wpdm_package id=’22582′]

Conclusion

In this tutorial I have explained how to use @NamedQuery and the advantages of using named queries. Using named queries are ideal when the queries are static and less likely modified at the tun time. Also it is easy to migrate an existing applications to spring data jpa.

If you have used named queries in your project, please share your experience and thoughts in the comments section. The best comments will be updated to this tutorial and will be select for free book promotions.

Filed Under: Spring Framework Tagged With: Spring Data JPA

  • « Previous Page
  • 1
  • 2
  • 3
  • 4
  • …
  • 24
  • Next Page »

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