SpringBoot开发环境搭建 整合mybatis+热部署+静态文件加载

项目源代码地址:https://gitee.com/codefarmer-zb/projects
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;
        }
    }
}

 

posted @ 2021-08-19 21:30  ITbing  阅读(416)  评论(0)    收藏  举报