官术网_书友最值得收藏!

  • Spring 5 Design Patterns
  • Dinesh Rajput
  • 305字
  • 2021-07-08 09:59:27

The Template Design pattern in Spring

Let's see how to go about using the Template Design pattern in spring:

  • Define the outline or skeleton of an algorithm
  1. Leave the details for specific implementations until later.
  2. Hide away large amounts of boilerplate code.
  • Spring provides many template classes:
  • JdbcTemplate
  • JmsTemplate
  • RestTemplate
  • WebServiceTemplate
  • Most hide low-level resource management

Let's look at the same code that we used earlier with Spring's JdbcTemplate and how it removes the boilerplate code.

Use JdbcTemplates to let your code the focus on the task:

    public Account getAccountById(long id) { 
      return jdbcTemplate.queryForObject( 
        "select id, name, amoount" + 
        "from account where id=?", 
         new RowMapper<Account>() { 
           public Account mapRow(ResultSet rs, 
            int rowNum) throws SQLException { 
              account = new Account(); 
              account.setId(rs.getLong("id")); 
              account.setName(rs.getString("name")); 
              account.setAmount(rs.getString("amount")); 
              return account; 
            } 
         }, 
      id); 
    } 

As you can see in the preceding code, this new version of getAccountById() is much simpler as compared to the boiler plate code, and here the method is focused on selecting an account from the database rather than creating a database connection, creating a statement, executing the query, handling the SQL exception, and finally closing the connection as well. With the template, you have to provide the SQL query and a RowMapper used for mapping the resulting set data to the domain object in the template's queryForObject() method. The template is responsible for doing everything for this operation, such as database connection and so on. It also hides a lot of boilerplate code behind the framework.

We have seen in this section how Spring attacks the complexities of Java development with the power of POJO-oriented development and patterns such as the DI pattern, the Aspect-using Proxy pattern, and the Template method design pattern.

In the next section, we will look at how to use a Spring container to create and manage the Spring beans in the application.

主站蜘蛛池模板: 遂平县| 策勒县| 大理市| 焦作市| 德兴市| 沾化县| 玉溪市| 仁怀市| 龙陵县| 永川市| 贡山| 济宁市| 浦北县| 苍溪县| 云梦县| 元江| 海晏县| 鄂伦春自治旗| 武宁县| 德州市| 永康市| 桃园市| 龙南县| 孝义市| 九寨沟县| 渝中区| 建阳市| 清镇市| 鄂伦春自治旗| 内丘县| 庄浪县| 宁蒗| 东阿县| 英吉沙县| 安宁市| 泗水县| 桑植县| 石阡县| 苍溪县| 德令哈市| 长泰县|