Spring Boot入門初體驗(2)--配置Druid與MyBatis鏈接Mysql

1.Maven配置Druid、Mybatis

在pom.xmljava

<!-- druid 數據源監控 -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.10</version>
		</dependency>
		<!-- mysql驅動包 -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<!-- mybatis -->
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>1.3.2</version>
		</dependency>

2.yml配置Druid、Mybatis

在application.ymlmysql

mybatis:
  #配置文件
  config-location: classpath:mybatis/mybatis-config.xml
  #Mapper文件
  mapper-locations: classpath:mybatis/mapper/*.xml  
  
spring:
   datasource:
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://localhost:3306/${dbName}?useUnicode=true&characterEncoding=utf8
    username: ${username}
    password:${password}
    initial-size: 10
    # 最大鏈接池數量
    max-active: 100
    # 最小鏈接池數量
    min-idle: 10
    # 配置獲取鏈接等待超時的時間
    max-wait: 60000

3.Druid映射鏈接池屬性

package com.example.common;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 配置druid初始化
 */
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        return druidDataSource;
    }
}

4.項目結構


application.yml
application-{name}.xml
可在主配置文件使用spring

spring:
  #激活數據源
  profiles:
    active: druid
	
spring:
  #不使用active 說明只是一個代碼塊
  profiles: druid
相關文章
相關標籤/搜索