1. 程式人生 > 其它 >SpringBoot開發環境搭建 整合mybatis+熱部署+靜態檔案載入

SpringBoot開發環境搭建 整合mybatis+熱部署+靜態檔案載入

1、熱部署devtools #在pom.xml中加入熱部署devtools依賴,版本跟專案start版本一致
<!--devtools 熱部署-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>
#在application.properties中加入配置、選擇熱部署main/java下的所有包與檔案
#熱部署devtools
spring.devtools.restart.enable=true
spring.devtools.restart.additional
-paths=src/main/java
#完成熱部署 2、配置 靜態資料夾 #在application.properties下配置本地檔案地址與對映關係
#配置 靜態資料夾
#path=網頁訪問根路徑:例如https://127.0.0.1:8080:專案名/upload/子包名/子子包/檔案
spring.resource.path=/upload/
#/upload/**  兩個**表示能訪問upload下的所有子包及檔案
spring.resource.path.pattern=/upload/**
#windows系統 檔案根路徑在d盤的upload
spring.resource.folder.windows=d:/upload/
#linux系統 檔案根路徑的upload
spring.resource.folder.linux=/upload/
#建立靜態資源訪問bean,就可以通過呼叫bean物件訪問靜態資源 *將配置檔案的屬性注入到bean的物件屬性 並生成get set方法,供其他方法建立並呼叫 *@Component將自動生成bean物件並託管給IOC容器
package com.example.springBoot.modules.test.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class
ResourceConfigBean { @Value("${spring.resource.path}") private String resourcePath; @Value("${spring.resource.path.pattern}") private String resourcePathPattern; @Value("${spring.resource.folder.windows}") private String localPathForWindow; @Value("${spring.resource.folder.linux}") private String localPathForLinux; public String getResourcePath() { return resourcePath; } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } public String getResourcePathPattern() { return resourcePathPattern; } public void setResourcePathPattern(String resourcePathPattern) { this.resourcePathPattern = resourcePathPattern; } public String getLocalPathForWindow() { return localPathForWindow; } public void setLocalPathForWindow(String localPathForWindow) { this.localPathForWindow = localPathForWindow; } public String getLocalPathForLinux() { return localPathForLinux; } public void setLocalPathForLinux(String localPathForLinux) { this.localPathForLinux = localPathForLinux; } }
#在Config/WebConfig.java中建立ResourceConfigBean 靜態資源bean *重寫 WebMvcConfigurer 介面的addResourceHandlers方法給不同的作業系統 賦予不同的路徑地址
package com.example.springBoot.modules.test.config;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jersey.ResourceConfigCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    @Autowired
    private ResourceConfigBean resourceConfigBean;
    /**
     * 建立靜態資原始檔夾 要重寫add
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        String systemName=System.getProperty("os.name");
        if (systemName.toLowerCase().startsWith("win")){
            registry.addResourceHandler(resourceConfigBean.getResourcePathPattern())
                    .addResourceLocations(ResourceUtils.FILE_URL_PREFIX+
                            resourceConfigBean.getLocalPathForWindow());
        }else{
            registry.addResourceHandler(resourceConfigBean.getResourcePathPattern())
                    .addResourceLocations(ResourceUtils.FILE_URL_PREFIX+
                            resourceConfigBean.getLocalPathForLinux());
        }
    }
}
#測試:開啟專案 網頁訪問:https://127.0.0.1/upload/picture/1.jpg 訪問到windows作業系統D:\upload\picture\1.jpg即為成功訪問 3、spring boot整合mybatis #在pom.xml匯入依賴,mysql、mybatis、pageHelper myabtis分頁輔助依賴、
<!--引用mysql依賴檔案-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.48</version>
</dependency>
<!-- mybatis spring-boot-mybatis依賴檔案-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.0</version>
</dependency>

<!-- pageHelper myabtis分頁輔助依賴-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.12</version>
</dependency>
#在application.properties中配置mysql四大屬性值 及連線池 及mybatis
# for data source
#配置資料庫
# mysql 5
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# mysql 6 +
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/springboot-test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

# hikari pool
# 連線池最大連線數,預設是10
spring.datasource.hikari.maximum-pool-size=20
# 最小空閒連線數量
spring.datasource.hikari.minimum-idle=5
# 空閒連線存活最大時間,預設600000(10分鐘)
spring.datasource.hikari.idle-timeout=180000
spring.datasource.hikari.auto-commit=true

# for mybatis
# 開啟駝峰轉下劃線
mybatis.configuration.map-underscore-to-camel-case=true
# 如果有單獨的 Mybatis 配置檔案,指定路徑
#mybatis.config-locations=classpath:config/SqlMapConfig.xml
# Mybatis 的 Xml 檔案中需要寫類的全路徑名,較繁瑣,可以配置自動掃描包路徑
#mybatis.type-aliases-package=com.thornBird.sbd.modules.*.entity
# 如果有 *Mapper.xml 檔案,配置路徑
#mybatis.mapper-locations=classpath:mapper/*Mapper.xml
#在WebConfig中建立Connector連線bean物件 和 servletWebServerFactory bean物件
package com.example.springBoot.modules.test.config;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jersey.ResourceConfigCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
    /**
     * 建立一個連線物件connector 設定http協議和埠號
     * @return
     */
    @Bean
    public Connector connector() {
        Connector connector = new Connector();
        connector.setPort(8080);
        connector.setScheme("http");
        return connector;
    }
    /**
     * 將建立的connector加入到IOC容器中
     * @return
     */
    @Bean
    public ServletWebServerFactory servletWebServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();
        factory.addAdditionalTomcatConnectors(connector());
        return factory;
    }
}
#建立cityDao @Repository和@Controller、@Service、@Component的作用差不多,都是把物件交給spring管理。 @Repository用在持久層的介面上,這個註解是將 介面的一個實現類交給spring管理。
package com.example.springBoot.modules.test.dao;
import com.example.springBoot.modules.test.entity.City;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface CityDao {
    @Insert("insert into test_city(city_name,local_city_name,country_id,date_created) " +
            "values(#{cityName},#{localCityName},#{countryId},#{dateCreated})")
    @Options(useGeneratedKeys = true, keyColumn = "city_id", keyProperty = "cityId")
    void insertCity(City city);
}
#建立cityservice介面
package com.example.springBoot.modules.test.service;
import com.example.springBoot.modules.common.entity.Result;
import com.example.springBoot.modules.test.entity.City;

public interface CityService {
    Result<City> insertCity(City city);
}
#建立cityserviceImpl實現類
package com.example.springBoot.modules.test.service.Impl;

import com.example.springBoot.modules.common.entity.Result;
import com.example.springBoot.modules.test.dao.CityDao;
import com.example.springBoot.modules.test.entity.City;
import com.example.springBoot.modules.test.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CityServiceImpl implements CityService {
    @Autowired
    private CityDao cityDao;
    @Override
    public Result<City> insertCity(City city) {
        city.setDateCreated(new Date());
        cityDao.insertCity(city);
        return new Result<>(Result.ResultCode.SUCCESS.code,
                "Insert success",city);
    }
}
#在common.entity包下建立Result泛型類、用於提供返回型別
package com.example.springBoot.modules.common.entity;

public class Result<T> {
    private int status;
    private String message;
    private T object;

    public Result() {
    }

    public Result(int status, String message) {
        this.status = status;
        this.message = message;
    }

    public Result(int status, String message, T object) {
        this.status = status;
        this.message = message;
        this.object = object;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getObject() {
        return object;
    }

    public void setObject(T object) {
        this.object = object;
    }
    /**
     * 列舉
     * 帶屬性的常量
     */
    public enum ResultCode{
        SUCCESS(200),
        FAILED(500);
        public int code;
        ResultCode(int code){
            this.code=code;
        }
    }
}