1. 程式人生 > >springboot 總結(二)

springboot 總結(二)

  1. JDBC
  • 加入依賴
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
  • 在resources 根目錄下建立application.yml 檔案
spring:
  datasource:
    username
: root password: abc123 url: jdbc:mysql://localhost:3306/test_db driver-class-name: com.mysql.jdbc.Driver

說明:

​ 資料來源相關的配置都在DataSourceProperties 裡面

@ConfigurationProperties(
    prefix = "spring.datasource"
)
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
private ClassLoader classLoader; private String name; private boolean generateUniqueName; private Class<? extends DataSource> type; private String driverClassName; private String url; private String username; private String password; private String jndiName;

​ 不同的springboot版本,預設使用的資料來源不同,如:com.zaxxer.hikari.HikariDataSource

public class HikariDataSource extends HikariConfig implements DataSource, Closeable {
    private static final Logger LOGGER = LoggerFactory.getLogger(HikariDataSource.class);
    private final AtomicBoolean isShutdown = new AtomicBoolean();
    private final HikariPool fastPathPool;
    private volatile HikariPool pool;

​ 不同的資料來源都實現了javax.sql.DataSource 介面

  • 自動配置原理

org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration 中配置了很多資料來源bean,如:

    @ConditionalOnClass({HikariDataSource.class})
    @ConditionalOnMissingBean({DataSource.class})
    @ConditionalOnProperty(
        name = {"spring.datasource.type"},
        havingValue = "com.zaxxer.hikari.HikariDataSource",
        matchIfMissing = true
    )
    static class Hikari {
        Hikari() {
        }

        @Bean
        @ConfigurationProperties(
            prefix = "spring.datasource.hikari"
        )
        public HikariDataSource dataSource(DataSourceProperties properties) {
            HikariDataSource dataSource = (HikariDataSource)DataSourceConfiguration.createDataSource(properties, HikariDataSource.class);
            if (StringUtils.hasText(properties.getName())) {
                dataSource.setPoolName(properties.getName());
            }

            return dataSource;
        }
    }

可以看到建立資料來源時會用到DataSourceProperties properties

  • DataSourceInitializer 可以用來執行sql 指令碼(在應用每次啟動的時候),在資料來源配置項中用schema 欄位指定sql 指令碼的位置
  1. 整合 druid
  • 加入依賴
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

  • 在資料來源配置檔案中用type 欄位指定資料來源
spring:
  datasource:
    username: root
    password: abc123
    url: jdbc:mysql://localhost:3306/test_db
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
  • 指定druid 其他屬性

    加入其他屬性

spring:
  datasource:
    username: root
    password: abc123
    url: jdbc:mysql://localhost:3306/test_db
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    initialSize: 5

​ 自定義一個配置類

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
}
  • 新增druid 監控功能
@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    // 配置Druid 監控
    // 配置一個管理後臺的servlet
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initMap = new HashMap<>();
        initMap.put("loginUsername", "admin");
        initMap.put("loginPassword", "123456");
        bean.setInitParameters(initMap);
        return bean;
    }

    //配置一個web監控filter
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        Map<String, String> initMap = new HashMap<>();
        initMap.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initMap);

        bean.setFilter(new WebStatFilter());

        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

}

訪問http://localhost:8080/druid 即可檢視監控

在這裡插入圖片描述

  1. 整合mybatis
  • 加入依賴
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>

  • 第一種方式,sql語句寫在註解中
@Mapper
public interface TestMapper {
    @select("select * from test_table where id = #{id}")
    public Person getPersonById(Integer id);
}

自動配置原理:

@Configuration
@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class})
@ConditionalOnBean({DataSource.class})
@EnableConfigurationProperties({MybatisProperties.class})
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class MybatisAutoConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(MybatisAutoConfiguration.class);
    private final MybatisProperties properties;
    private final Interceptor[] interceptors;
    private final ResourceLoader resourceLoader;
    private final DatabaseIdProvider databaseIdProvider;
    private final List<ConfigurationCustomizer> configurationCustomizers;

    public MybatisAutoConfiguration(MybatisProperties properties, ObjectProvider<Interceptor[]> interceptorsProvider, ResourceLoader resourceLoader, ObjectProvider<DatabaseIdProvider> databaseIdProvider, ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider) {
        this.properties = properties;
        this.interceptors = (Interceptor[])interceptorsProvider.getIfAvailable();
        this.resourceLoader = resourceLoader;
        this.databaseIdProvider = (DatabaseIdProvider)databaseIdProvider.getIfAvailable();
        this.configurationCustomizers = (List)configurationCustomizersProvider.getIfAvailable();
    }

SqlSessionFactory 宣告在MybatisAutoConfiguration 中,MybatisProperties 對應配置檔案,在MybatisProperties中可以看到它會讀取字首為"mybatis" 的配置

這種方式,可以通過宣告一個ConfigrationCustomizer 來完成全域性配置,如開啟駝峰命名法

Mapper 很多的時候可以使用,@MapperScan 註解來掃描

  • 第二種方式,使用配置檔案

在配置檔案中加入字首為"mybatis" 的配置即可,config-location 指定全域性配置檔案的位置,mapper-location 指定對映檔案的位置