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

后端 未结 3 898
后悔当初
后悔当初 2021-02-07 06:18

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 ar

相关标签:
3条回答
  • 2021-02-07 06:32

    These kind of classes are used to simplify the functionality, letting low level issues asside of, for example, connecting to the database (all the dirty work is done by the jdbcTemplate class).

    The JdbcTemplate simplifies the use of JDBC and helps to avoid common errors. It executes core JDBC workflow, leaving application code to provide SQL and extract results. This class executes SQL queries or updates, initiating iteration over ResultSets and catching JDBC exceptions and translating them to the generic, more informative exception hierarchy.

    The only thing you need to actually implement are the CallBack methods. Implementing only callback methods let your code clean. Your only concern is to execute your business logic.

    0 讨论(0)
  • 2021-02-07 06:33

    They are called template as use the Template method pattern.

    Basically the idea is define the operation needed to do something in an abstract class or super class then implement a class that use the operation previous defined.

    In the case of spring allow that operation that always need to be done for an specific purpose be done automatically, (open connection, obtain for pool, translation, execution, close connection), then user only need to call methods without worries about the previous tasks.

    0 讨论(0)
  • 2021-02-07 06:53

    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.

    0 讨论(0)
提交回复
热议问题