What are template classes in Spring Java? Why are they called templates? For example jdbc-template, jms-template etc

Horse Voice picture Horse Voice · Jan 31, 2014 · Viewed 10.8k times · Source

I'm new to Java. I've only been programming it for about a year. What does Spring mean by the use of templates? In Spring, there is jdbc-templates, jms-templates etc.. What are template classes in java? Are they a special kind of design pattern or what?

Thank you in advance.

Answer

Angular University picture Angular University · Feb 1, 2014

Spring templates are a way to eliminate boilerplate code that is needed to correctly use many APIs such as JDBC, JMS, transactions, etc. Boilerplate code is setup and error handling code that needs to be written in order to use correctly a API.

For example in JDBC, for executing a query the template will take care of the all setting of the connection, preparing the statement, releasing the connection after the query is done, handling exceptions all of which is non-trivial and easy to get wrong.

To the template you just need to pass in the query that you want to run, and the rest is taken care by the template.

Take the example on this blog post, a program of 80 lines executing a query in plain jdbc was reduced to 20 lines when using the spring JDBC template.