1.2 Spring Boot - xphsc/EasyJdbc GitHub Wiki

1.2 Spring Boot 集成

Spring Boot 在微服务领域中已经成为主流。

这里介绍通用 easyjdbc 如何同 Spring Boot 进行集成。

为了能适应各种情况的用法,这里也提供了多种集成方式,基本上分为两大类。

基于 starter 的自动配置 基于 @EnableEasyJdbc 注解的手工配置

1.2.1 easyjdbc-spring-boot-starter -> 2.x基于easyjdbc2.x版本->jdk1.8 函数表达式

在 starter 的逻辑中,如果你没有使用 @EnableEasyJdbc 注解

@EnableEasyJdbc //1.0.7版本以上无需注解自动扫描
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application .class, args);
    }

}

以后会考虑增加其他方式。 在开始配置前,先添加相关的依赖。 正常情况下,Spring boot 和 easyjdbc 的集成环境中,应该已经存在下面的依赖:

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <version>版本号</version>
    </dependency>

你只需要添加通用 easyjdbc 提供的 starter 就完成了最基本的集成,依赖如下:

2.x基于easyjdbc2.x版本->jdk1.8 函数表达式
<dependency>
    <groupId>cn.xphsc.boot</groupId>
    <artifactId>easyjdbc-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>

注意:获取版本 https://central.sonatype.com/artifact/cn.xphsc.boot/easyjdbc-spring-boot-starter

你需要对通用 easyjdbc 进行配置,你可以在 Spring Boot 的配置文件中配置 easyjdbc数据库方言 前缀的配置。

例如在 yml 格式中配置:

easyjdbc:
 dialect: mysql
 
在 properties 配置中:
easyjdbc.dialect= mysql

注意: 从easyjdbc1.0.6及easyjdbc-spring-boot-starter1.0.4以上版本需默认添加以下配置

//如果你的项目包名是以com开头无需配置以下配置,默认扫描com.*, 建议配置到扫描到DAO的包名
easyjdbc:
 basePackage: com.xphsc.*.dao 
 注意: 从easyjdbc1.1.X及easyjdbc-spring-boot-starter1.1.X以上版本增加以下配置
在 properties 配置中:
//本地缓存
easyjdbc.use-local-cache=  true/false
//日志打印(info日志)
easyjdbc.show-sql=  true/false

注意:支持注解扫描@DaoScan

在启动类上(无需再配置easyjdbc.basePackages: com.xphsc.*.dao )
@DaoScan(basePackages = "com.*")

使用 SQL日志打印配置(debug)

logging:
  level:
   //设置SQL日志debug,主要接口(dao层) sql日志打印
    com.xphsc.easyjdbc.dao: debug 

配置自定义插件实现EasyJdbcInterceptor 【2.0.5】

//实现插件

public class SlowSqlInterceptor implements EasyJdbcInterceptor {

    private final long thresholdNanos;
    private final Log logger = LogFactory.getLog(SlowSqlInterceptor.class);

    public SlowSqlInterceptor(long thresholdMillis) {
        this.thresholdNanos = thresholdMillis * 1_000_000L;
    }

    @Override
    public Object afterExecution(SqlExecutionContext context, Object result) {
        if (context.getElapsedTimeNanos() >= thresholdNanos && context.getSql() != null) {
            logger.warn("Slow SQL detected, took " + (context.getElapsedTimeNanos() / 1_000_000D)
                    + " ms, type=" + context.getExecutionType()
                    + ", sql=" + context.getSql());
        }
        return result;
    }
}

//注入插件
@Bean("slowSqlInterceptor")
public EasyJdbcInterceptor slowSqlInterceptor() {
return new SlowSqlInterceptor(2);
}
//配置插件生效
easyjdbc:
 dialect: mysql
 basePackages: com.x.x.dao
 interceptorBeans:
  - slowSqlInterceptor
}

⚠️ **GitHub.com Fallback** ⚠️