JdbcTemplate 是Spring提供的一套JDBC模板框架,利用AOP 技术来解决直接使用JDBC时大量重复代码的问题。JdbcTemplate虽然没有MyBatis 那么灵活,但是直接使用JDBC要方便很多。Spring Boot中对Jdbc Template的使用提供了自动化配置类JdbcTemplateAutoConfiguration,部分源码如下:

 1 package org.springframework.boot.autoconfigure.jdbc;
 2 
 3 // 省略 import 行
 4 
 5 @Configuration
 6 // 仅在类 DataSource,JdbcTemplate 存在于 classpath 时生效,
 7 // 这两个类属于 spring-jdbc
 8 @ConditionalOnClass({ DataSource.class, JdbcTemplate.class })
 9 // 仅在单数据源bean存在时才生效
10 @ConditionalOnSingleCandidate(DataSource.class)
11 // 在数据源自动配置应用之后应用
12 @AutoConfigureAfter(DataSourceAutoConfiguration.class)
13 // 确保前缀为 spring.jdbc 的配置参数被加载到 bean JdbcProperties
14 @EnableConfigurationProperties(JdbcProperties.class)
15 public class JdbcTemplateAutoConfiguration {
16 
17     // 内嵌配置类
18     @Configuration
19     static class JdbcTemplateConfiguration {
20 
21         private final DataSource dataSource;
22 
23         private final JdbcProperties properties;
24 
25         JdbcTemplateConfiguration(DataSource dataSource, JdbcProperties properties) {
26             this.dataSource = dataSource;
27             this.properties = properties;
28         }
29 
30        // 定义 bean  JdbcTemplate jdbcTemplate       
31         @Bean
32         @Primary
33         // 仅在此bean没有被定义时才定义
34         @ConditionalOnMissingBean(JdbcOperations.class)
35         public JdbcTemplate jdbcTemplate() {
36             JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource);
37             JdbcProperties.Template template = this.properties.getTemplate();
38             jdbcTemplate.setFetchSize(template.getFetchSize());
39             jdbcTemplate.setMaxRows(template.getMaxRows());
40             if (template.getQueryTimeout() != null) {
41                 jdbcTemplate
42                         .setQueryTimeout((int) template.getQueryTimeout().getSeconds());
43             }
44             return jdbcTemplate;
45         }
46 
47     }
48 
49     // 内嵌配置类
50     @Configuration
51     // 导入 JdbcTemplateConfiguration 配置类
52     @Import(JdbcTemplateConfiguration.class)
53     static class NamedParameterJdbcTemplateConfiguration {
54 
55         // 定义 bean NamedParameterJdbcTemplate namedParameterJdbcTemplate
56         @Bean
57         @Primary
58         @ConditionalOnSingleCandidate(JdbcTemplate.class)
59         @ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
60         public NamedParameterJdbcTemplate namedParameterJdbcTemplate(
61                 JdbcTemplate jdbcTemplate) {
62             return new NamedParameterJdbcTemplate(jdbcTemplate);
63         }
64 
65     }
66       ......  
67 }    
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-31
  • 2022-12-23
  • 2021-07-17
  • 2021-11-15
  • 2021-06-07
  • 2019-12-14
猜你喜欢
  • 2021-11-14
  • 2021-09-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-05
  • 2022-12-23
相关资源
相似解决方案