Spring - Initializing a Spring Bean

It is often required to run some custom code on initialization of a Spring bean. e.g. to check for mandatory properties or establish initial connections. Spring provides a few constructs to initialize the beans after they are injected with the properties.

Groovy - How to Execute Groovy Scripts in Sublime Text?

This article covers the steps to setup Sublime Text to execute Groovy scripts.

How to Read Files in Groovy?

This article shows various ways of reading a text file in groovy.

How to Create Web Notifications

Web Notifications provide ways for websites to display notifications to users e.g. alerting the user about a business event or success/failure of an asynchronous operation.

Spring - Lookup Method or Method Injection

Most common injection mechanisms used in Spring are Constructor and Property injections. In both the mechanisms, the injection happens only once during the initialization of the Bean. They also require a concrete method defined e.g. a constructor method for constructor injections and a setter method for property injection.

How to Create Custom Namespaces and Handlers in Spring

Custom namespaces in spring are a way to replace the complex bean definitions with a more user-friendly configuration.

Spring itself provides several namespaces out of the box. e.g.

Localization with Spring

Localization enables applications to cater to users of different locations and languages. Spring, as usual, has support for this aspect as well.

Before jumping into what Spring has to offer, let's explore what we get from Java itself.

Spring Boot - How to Create a Deployable War

Spring boot, by default, enables you to create standalone applications through simple, minimal configurations. And due to its self-contained nature, it naturally enables building microservices.

Spring starters are poms (if using maven) that

Spring Cache - Part 5 - CacheEvict

In the Spring Cache series so far (Part1, Part2, Part3, Part4), we have seen examples where the data is getting added to the cache through the use of @Cacheable and @CachePut. But, what about removing data from cache? Consider a call to delete the record from Service or DB, in which case, we would also want to delete that record from the cache.

Deep Copy Java Objects through Serialization

When it comes to deep copy or cloning an object, the first thing that comes to mind is to override the clone() method and set each field manually. This can be pretty cumbersome to implement for complex objects or if you have to do this for a lot of them.

A simpler way to deep copy an object is to serialize it and then deserialize to get a new instance.
Let's check out a few examples.

Deep Copy using Spring's SerializationUtils


//import org.springframework.util.SerializationUtils;

 byte[] sourceInBytes = SerializationUtils.serialize(sourceInstance);
 Object newInstance = SerializationUtils.deserialize(sourceInBytes);

Since we are using java serialization here, the Class needs to implement Serializable.

Deep Copy using Apache Commons Lang SerializationUtils

//import org.apache.commons.lang.SerializationUtils
 Object newInstance = SerializationUtils.clone(sourceInstance);

Just like above example, this one needs the POJO to implement Serializable.

Deep Copy through JSON serialization

//import org.codehaus.jackson.map.ObjectMapper;
//import org.codehaus.jackson.map.ObjectMapper.DefaultTyping;
 
 ObjectMapper mapper = new ObjectMapper();
 mapper.enableDefaultTyping(DefaultTyping.NON_FINAL);
 String jsonSource = mapper.writeValueAsString(sourceInstance);
 MyClass newInstance = mapper.readValue(jsonSource, MyClass.class);

The advantage with JSON is that the Class need not implement a Serializable interface. It just needs to be a POJO with a public no-arg constructor and getters/setters for the properties. enableDefaultTyping here ensures that the Polymorphic Type Handling is taken care of.

Spring Cache - Part 4 - CachePut


There are scenarios, unlike retrievals, where you do not want to skip the execution of the method e.g. insert/update of a record. Such methods should not be marked as Cacheable. But, you might still want to cache the result of these methods, in order to avoid unnecessary retrievals in future calls.

Spring Cache - Part 3 - Conditional Cache


In this part of the tutorial, we will see how data can be cached conditionally. (If you haven't checked the previous parts, please visit Part 1 and Part 2. They contain sample code that the examples below refer)

Spring Cache - Part 2 - Cache Keys

In part 1 of the post, we looked at how data can be cached through simple configuration. In this part, we are going to explore the cache keys.

Spring Cache - Part 1 - Introduction


Caching is an extremely important aspect of applications that care about lower latencies. There are a multitude of rules one has to adhere to while setting up a cache, in order to optimize the performance; but not overdo it. We will not get into those details in this post. Our focus would be on what Spring provides to enable caching in your applications.

JSON Property Name Customization in Jackson using PropertyNamingStrategy

Jackson is one of the most popular java libraries for serialization/deserialization of POJOs to/from JSON. By default, Jackson derives the JSON element names from the getter/setter method names of the POJO. e.g. getActorName() is translated to actorName in the resulting JSON.

How to Timeout JDBC Queries

JDBC queries by default do not have any timeout, which means that a query can block the thread for an unlimited amount time; of course, depending upon the DB load and the cost of the query. It is a good practice to timeout these queries if they can take longer than a certain amount of time.

Timeout on individual Queries


JDBC statements can be configured for timeouts, in seconds. When timeouts are set, the driver would wait for the given number of seconds for the query to execute (i.e. executeQuery and executeUpdate) and throw an SQLTimeoutException if doesn't respond within that time.

Here are a couple of examples.

Statement stmt = connection.prepareStatement("SELECT * FROM BOOKS");
stmt.setQueryTimeout(10);//Timeout of 10 seconds

//This would throw an SQLTimeoutException if it exceeds 10 seconds
ResultSet result = stmt.executeQuery();

PreparedStatement stmt = connection.prepareStatement("UPDATE BOOKS SET RETURNED = ? WHERE BID = ?");
stmt.setBoolean(1, true);
stmt.setString(2, "B1234");
stmt.setQueryTimeout(5);//Timeout of 5 seconds
  
//This would throw an SQLTimeoutException if it exceeds 5 seconds
stmt.executeUpdate();

Global Timeout (JDBC Driver Level)


If you need to set the same timeout for all query executions, then it can be set directly on the drivers. However, the options would differ from driver to driver.
Here is an example of timeouts set on the Oracle Thin Driver

Properties properties = new Properties();
properties.setProperty("user", "scott");
properties.setProperty("password", "tiger");
//This timeout is in milliseconds, but can vary for other drivers
properties.setProperty(OracleConnection.CONNECTION_PROPERTY_THIN_READ_TIMEOUT, "2000");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:1521:SID", properties);

Spring JDBC timeouts


If you are using Spring JDBC, where you do not have direct control over the JDBC statements, JDBCTemplate also provides an option to setQueryTimeOut. If set to -1, it takes the JDBC driver's default setting for timeouts (which is covered above).
getJdbcTemplate().setQueryTimeout(5);
getJdbcTemplate().update("UPDATE BOOKS ...", sqlParamSource);





Tarlog - Eclipse Plugin for Windows

Tarlog is a plugin for eclipse that provides some useful features if you are working on a Windows machine. It allows you to Copy Path, Open Shell or Open Explorer on the selected file or folder in the project. It also allows changing the font of the editor through Ctrl++ and Ctrl-- keys.

Overriding Spring Beans with Aliases


The most common approach followed for overriding a spring bean is to define a new bean, with the same id as the original bean, in a separate XML file. During context initialization, Spring would register the last bean found for the id, and use it for all the injections.

I dislike this approach for two reasons.