21.1. 從零開始學springboot-搭建一個可以上線的項目結構-多模塊篇(2)

前言

接從零開始學springboot-搭建一個可以上線的項目結構-多模塊篇(1)

mr-service

目錄結構


15.png

mr-service這個模塊簡單介紹下,impl內放的是實現(xiàn)類筐喳,外面定義的是接口催式,這也是為了遵循基本的開發(fā)規(guī)范~

RedisService (redis服務類函喉,作者沒有定義接口,同學們自行判斷)

package com.mrcoder.mrservice;
import com.mrcoder.mrutils.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
/**
 * redis 測試業(yè)務層
 */
@Service
public class RedisService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisUtil redisUtil;//內部封裝了 RedisTemplate<String, Object>
    /**
     * 測試存儲 String 類型數(shù)據(jù)
     */
    public void setValue(String key, String string) {
        redisUtil.set(key, string);
    }
    /**
     * 測試讀取 String 類型數(shù)據(jù)
     */
    public Object getValue(String key) {
        boolean flag = redisUtil.hasKey(key);
        Object rs = null;
        if (flag) {
            rs = redisUtil.get(key);
        }
        return rs;
    }
}

StudentService

package com.mrcoder.mrservice;
import com.mrcoder.mrentity.entity.master.Student;
import java.util.List;
public interface StudentService {
    public List<Student> getListByAnno();
    public List<Student> getList();
    public Student getById(Long id);
    public Integer save(Student s);
    public Integer update(Student s);
    public Integer delete(Long id);
    public void trans(int code);
}

TeacherService (作者偷懶荣月,就不實現(xiàn)Teacher服務類了)

package com.mrcoder.mrservice;
public class TeacherService {
}

impl/StudentServiceImpl

package com.mrcoder.mrservice.impl;
import com.mrcoder.mrentity.entity.master.Student;
import com.mrcoder.mrentity.entity.slave.Teacher;
import com.mrcoder.mrentity.mapper.master.StudentMapper;
import com.mrcoder.mrentity.mapper.slave.TeacherMapper;
import com.mrcoder.mrservice.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    public List<Student> getListByAnno() {
        return studentMapper.getListByAnno();
    }
    public List<Student> getList() {
        return studentMapper.getList();
    }
    public Student getById(Long id) {
        return studentMapper.getById(id);
    }
    public Integer save(Student s) {
        return studentMapper.insert(s);
    }
    public Integer update(Student s) {
        return studentMapper.update(s);
    }
    public Integer delete(Long id) {
        return studentMapper.delete(id);
    }
    @Transactional
    public void trans(int code) {
        Student s1 = new Student();
        s1.setAge(10);
        s1.setGrade(10);
        s1.setName("s1");
        studentMapper.insert(s1);

        Teacher t1 = new Teacher();
        t1.setAge(10);
        t1.setName("t1");
        t1.setCourse(10);
        teacherMapper.insert(t1);
        int result = 1 / code;
    }
}

impl/TeacherServiceImpl (偷懶不寫管呵,咋地)

package com.mrcoder.mrservice.impl;
public class TeacherServiceImpl {
}

mr-utils

目錄結構


16.png

redis/RedisUtil

package com.mrcoder.mrutils.redis;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
 * @Description: redis 工具類
 */
public class RedisUtil {
    private RedisTemplate<String, Object> redisTemplate;
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    /**
     * 指定緩存失效時間
     *
     * @param key  鍵
     * @param time 時間(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 根據(jù)key 獲取過期時間
     *
     * @param key 鍵 不能為null
     * @return 時間(秒) 返回0代表為永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判斷key是否存在
     *
     * @param key 鍵
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 刪除緩存
     *
     * @param key 可以傳一個值 或多個
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }
    /**
     * 普通緩存獲取
     *
     * @param key 鍵
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    /**
     * 普通緩存放入
     *
     * @param key   鍵
     * @param value 值
     * @return true成功 false失敗
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 普通緩存放入并設置時間
     *
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒) time要大于0 如果time小于等于0 將設置無限期
     * @return true成功 false 失敗
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 遞增
     *
     * @param key   鍵
     * @param delta 要增加幾(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞增因子必須大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }
    /**
     * 遞減
     *
     * @param key   鍵
     * @param delta 要減少幾(小于0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞減因子必須大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }
    /**
     * HashGet
     *
     * @param key  鍵 不能為null
     * @param item 項 不能為null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
    /**
     * 獲取hashKey對應的所有鍵值
     *
     * @param key 鍵
     * @return 對應的多個鍵值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
    /**
     * HashSet
     *
     * @param key 鍵
     * @param map 對應多個鍵值
     * @return true 成功 false 失敗
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * HashSet 并設置時間
     *
     * @param key  鍵
     * @param map  對應多個鍵值
     * @param time 時間(秒)
     * @return true成功 false失敗
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
     *
     * @param key   鍵
     * @param item  項
     * @param value 值
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 向一張hash表中放入數(shù)據(jù),如果不存在將創(chuàng)建
     *
     * @param key   鍵
     * @param item  項
     * @param value 值
     * @param time  時間(秒)  注意:如果已存在的hash表有時間,這里將會替換原有的時間
     * @return true 成功 false失敗
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 刪除hash表中的值
     *
     * @param key  鍵 不能為null
     * @param item 項 可以使多個 不能為null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }
    /**
     * 判斷hash表中是否有該項的值
     *
     * @param key  鍵 不能為null
     * @param item 項 不能為null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }
    /**
     * hash遞增 如果不存在,就會創(chuàng)建一個 并把新增后的值返回
     *
     * @param key  鍵
     * @param item 項
     * @param by   要增加幾(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }
    /**
     * hash遞減
     *
     * @param key  鍵
     * @param item 項
     * @param by   要減少記(小于0)
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }
    /**
     * 根據(jù)key獲取Set中的所有值
     *
     * @param key 鍵
     * @return
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 根據(jù)value從一個set中查詢,是否存在
     *
     * @param key   鍵
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 將數(shù)據(jù)放入set緩存
     *
     * @param key    鍵
     * @param values 值 可以是多個
     * @return 成功個數(shù)
     */
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    /**
     * 將set數(shù)據(jù)放入緩存
     *
     * @param key    鍵
     * @param time   時間(秒)
     * @param values 值 可以是多個
     * @return 成功個數(shù)
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) expire(key, time);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    /**
     * 獲取set緩存的長度
     *
     * @param key 鍵
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    /**
     * 移除值為value的
     *
     * @param key    鍵
     * @param values 值 可以是多個
     * @return 移除的個數(shù)
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
 //===============================list=================================
    /**
     * 獲取list緩存的內容
     *
     * @param key   鍵
     * @param start 開始
     * @param end   結束  0 到 -1代表所有值
     * @return
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 獲取list緩存的長度
     *
     * @param key 鍵
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    /**
     * 通過索引 獲取list中的值
     *
     * @param key   鍵
     * @param index 索引  index>=0時, 0 表頭喉童,1 第二個元素撇寞,依次類推;index<0時堂氯,-1,表尾牌废,-2倒數(shù)第二個元素咽白,依次類推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 將list放入緩存
     *
     * @param key   鍵
     * @param value 值
     * @param time  時間(秒)
     * @return
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) expire(key, time);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 根據(jù)索引修改list中的某條數(shù)據(jù)
     *
     * @param key   鍵
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 移除N個值為value
     *
     * @param key   鍵
     * @param count 移除多少個
     * @param value 值
     * @return 移除的個數(shù)
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
}

web-service

以上,我們完善了幾個公共的子模塊鸟缕,最后晶框,我們來完善下真正的服務子模塊,也就是web-service模塊

config/datasource/DataSourceConfig

package com.mrcoder.webservice.config.datasource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jta.atomikos.AtomikosDataSourceBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import javax.sql.DataSource;
import java.util.Properties;
/**
 * 數(shù)據(jù)源配置類
 */
@Configuration
public class DataSourceConfig {
    @Autowired
    private Environment env;
    @Value("${spring.datasource.type}")
    private String dataSourceType;
    /**
     * 配置主數(shù)據(jù)源懂从,多數(shù)據(jù)源中必須要使用@Primary指定一個主數(shù)據(jù)源
     * 其次DataSource里用的是DruidXADataSource 授段,而后注冊到AtomikosDataSourceBean并且返回
     */
    @Primary
    @Bean(name = "masterDataSource")
    @DependsOn({"txManager"})
    public DataSource masterDataSource() {
        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        Properties prop = build(env, "spring.datasource.druid.master.");
        ds.setXaDataSourceClassName(dataSourceType);
        ds.setPoolSize(5);
        ds.setXaProperties(prop);
        return ds;
    }
    /**
     * 配置次數(shù)據(jù)源
     * 其次DataSource里用的是DruidXADataSource ,而后注冊到AtomikosDataSourceBean并且返回
     */
    @Bean(name = "slaveDataSource")
    @DependsOn({"txManager"})
    public DataSource slaveDataSource() {
        AtomikosDataSourceBean ds = new AtomikosDataSourceBean();
        Properties prop = build(env, "spring.datasource.druid.slave.");
        ds.setXaDataSourceClassName(dataSourceType);
        ds.setPoolSize(5);
        ds.setXaProperties(prop);
        return ds;
    }
    private Properties build(Environment env, String prefix) {
        Properties prop = new Properties();
        prop.put("name", env.getProperty(prefix + "name"));
        prop.put("url", env.getProperty(prefix + "url"));
        prop.put("username", env.getProperty(prefix + "username"));
        prop.put("password", env.getProperty(prefix + "password"));
        prop.put("driverClassName", env.getProperty(prefix + "driverClassName", ""));
        prop.put("filters", env.getProperty(prefix + "filters"));
        prop.put("maxActive", env.getProperty(prefix + "maxActive", Integer.class));
        prop.put("initialSize", env.getProperty(prefix + "initialSize", Integer.class));
        prop.put("maxWait", env.getProperty(prefix + "maxWait", Integer.class));
        prop.put("minIdle", env.getProperty(prefix + "minIdle", Integer.class));
        prop.put("timeBetweenEvictionRunsMillis",
                env.getProperty(prefix + "timeBetweenEvictionRunsMillis", Integer.class));
        prop.put("minEvictableIdleTimeMillis", env.getProperty(prefix + "minEvictableIdleTimeMillis", Integer.class));
        prop.put("validationQuery", env.getProperty(prefix + "validationQuery"));
        prop.put("testWhileIdle", env.getProperty(prefix + "testWhileIdle", Boolean.class));
        prop.put("testOnBorrow", env.getProperty(prefix + "testOnBorrow", Boolean.class));
        prop.put("testOnReturn", env.getProperty(prefix + "testOnReturn", Boolean.class));
        prop.put("poolPreparedStatements", env.getProperty(prefix + "poolPreparedStatements", Boolean.class));
        prop.put("maxOpenPreparedStatements", env.getProperty(prefix + "maxOpenPreparedStatements", Integer.class));
        return prop;
    }
}

config/datasource/MasterSqlSessionTemplateConfig

package com.mrcoder.webservice.config.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
 * MasterSqlSessionTemplateConfig配置類
 */
@Configuration
//下面的sqlSessionTemplateRef 值需要和生成的SqlSessionTemplate bean name相同番甩,如果沒有指定name,那么就是方法名
@MapperScan(basePackages = {"com.mrcoder.mrentity.mapper.master"}, sqlSessionTemplateRef = "masterSqlSessionTemplate")
public class MasterSqlSessionTemplateConfig {
    @Value("${mybatis.mapper-locations}")
    private String mapper_location;
    @Value("${mybatis.type-aliases-package}")
    private String type_aliases_package;
    @Value("${mybatis.configuration.map-underscore-to-camel-case}")
    private boolean mapUnderscoreToCamelCase;
    //將MybatisConfig類中初始化的對象注入進來
    @Autowired
    private ConfigurationCustomizer customizer;
    private Logger logger = LoggerFactory.getLogger(MasterSqlSessionTemplateConfig.class);
    /**
     * 自定義sqlSessionFactory配置(因為沒有用到MybatisAutoConfiguration自動配置類侵贵,需要手動配置)
     */
    @Bean
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource dataSource) throws Exception {
        logger.info("mapper文件地址為:{}", mapper_location);
        //在基本的 MyBatis 中,session 工廠可以使用 SqlSessionFactoryBuilder 來創(chuàng)建。
        //而在 MyBatis-spring 中,則使用SqlSessionFactoryBean 來替代:
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //如果重寫了 SqlSessionFactory 需要在初始化的時候手動將 mapper 地址 set到 factory 中缘薛,否則會報錯:
        //org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper_location));
        //下面這個setTypeAliasesPackage無效窍育,是mybatis集成springBoot的一個bug,暫時未能解決
        bean.setTypeAliasesPackage(type_aliases_package);
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        logger.info("mybatis配置駝峰轉換為:{}", mapUnderscoreToCamelCase);
        configuration.setMapUnderscoreToCamelCase(mapUnderscoreToCamelCase);
        //因為沒有用mybatis-springBoot自動裝配宴胧,所以需要手動將configuration裝配進去漱抓,要不然自定義的map key駝峰轉換不起作用
        customizer.customize(configuration);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }
    /**
     * SqlSessionTemplate 是 SqlSession接口的實現(xiàn)類,是spring-mybatis中的恕齐,實現(xiàn)了SqlSession線程安全
     */
    @Bean
    public SqlSessionTemplate masterSqlSessionTemplate(@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}

config/datasource/SlaveSqlSessionTemplateConfig

package com.mrcoder.webservice.config.datasource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
 * SlaveSqlSessionTemplateConfig配置類
 */
@Configuration
@MapperScan(basePackages = {"com.mrcoder.mrentity.mapper.slave"}, sqlSessionTemplateRef = "slaveSqlSessionTemplate")
public class SlaveSqlSessionTemplateConfig {
    @Value("${mybatis.mapper-locations}")
    private String mapper_location;
    @Bean
    public SqlSessionFactory slaveSqlSessionFactory(@Qualifier("slaveDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //如果重寫了 SqlSessionFactory 需要在初始化的時候手動將 mapper 地址 set到 factory 中乞娄,否則會報錯:
        //org.apache.ibatis.binding.BindingException: Invalid bound statement (not found)
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapper_location));
        return bean.getObject();
    }
    @Bean
    public SqlSessionTemplate slaveSqlSessionTemplate(@Qualifier("slaveSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }
}

config/datasource/TransactionManagerConfig

package com.mrcoder.webservice.config.datasource;
import com.atomikos.icatch.jta.UserTransactionImp;
import com.atomikos.icatch.jta.UserTransactionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.transaction.jta.JtaTransactionManager;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
/**
 * 多數(shù)據(jù)源事務管理器配置類
 */
@Configuration
public class TransactionManagerConfig {
    /**
     * 分布式事務使用JTA管理,不管有多少個數(shù)據(jù)源只要配置一個 JtaTransactionManager
     *
     * @return
     */
    @Bean(name = "atomikosTransactionManager", initMethod = "init", destroyMethod = "close")
    public TransactionManager atomikosTransactionManager() throws Throwable {
        UserTransactionManager userTransactionManager = new UserTransactionManager();
        userTransactionManager.setForceShutdown(false);
        return userTransactionManager;
    }
    @Bean(name = "txManager")
    @DependsOn({ "userTransaction", "atomikosTransactionManager" })
    public JtaTransactionManager transactionManager() throws Throwable {
        UserTransaction userTransaction = userTransaction();
        TransactionManager atomikosTransactionManager = atomikosTransactionManager();
        return new JtaTransactionManager(userTransaction, atomikosTransactionManager);
    }
    @Bean(name = "userTransaction")
    public UserTransaction userTransaction() throws Throwable {
        UserTransactionImp userTransactionImp = new UserTransactionImp();
        userTransactionImp.setTransactionTimeout(10000);
        return userTransactionImp;
    }
}

config/wrapper/CustomWrapper

package com.mrcoder.webservice.config.wrapper;
import com.google.common.base.CaseFormat;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import java.util.Map;
/**
 * @Description: 自定義wrapper處理spring boot + mybatis返回結果為map時的key值轉換為駝峰
 */
public class CustomWrapper extends MapWrapper {
    public CustomWrapper(MetaObject metaObject, Map<String, Object> map) {
        super(metaObject, map);
    }
    @Override
    public String findProperty(String name, boolean useCamelCaseMapping) {
        if (useCamelCaseMapping) {
            return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
        }
        return name;
    }
}

config/wrapper/MapWrapperFactory

package com.mrcoder.webservice.config.wrapper;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import java.util.Map;
/**
 * 實現(xiàn)接口 ObjectWrapperFactory,通過包裝工廠來創(chuàng)建自定義的wrapper
 */
public class MapWrapperFactory implements ObjectWrapperFactory {
    @Override
    public boolean hasWrapperFor(Object object) {
        return object != null && object instanceof Map;
    }
    @Override
    public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
        return new CustomWrapper(metaObject, (Map) object);
    }
}

config/DruidConfig

package com.mrcoder.webservice.config;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * 配置 Druid登陸配置(白名單等)
 */
@Configuration
public class DruidConfig {
    @Value("${spring.druid.name}")
    private String name;
    @Value("${spring.druid.pass}")
    private String pass;
    private Logger logger = LoggerFactory.getLogger(DruidConfig.class);
    /**
     * 配置 Druid控制臺 白名單显歧、黑名單仪或、用戶名、密碼等
     * 訪問地址  ip+port/projectContextPath/druid/index.html
     */
    @Bean
    public ServletRegistrationBean DruidStatViewServlet() {
        logger.info("servletRegistrationBean configure is starting...");
        //org.springframework.boot.context.embedded.ServletRegistrationBean提供類的進行注冊.
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        //添加初始化參數(shù)
        servletRegistrationBean.addInitParameter("allow", "*");
        servletRegistrationBean.addInitParameter("loginUsername", name);
        servletRegistrationBean.addInitParameter("loginPassword", pass);
        //是否可以重置
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }
    /**
     * 注冊一個:filterRegistrationBean
     */
    @Bean
    public FilterRegistrationBean druidStatFilter2() {
        logger.info("filterRegistrationBean configure is starting...");
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        //添加過濾規(guī)則.
        filterRegistrationBean.addUrlPatterns("/*");
        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

config/MybatisConfig

package com.mrcoder.webservice.config;
import com.mrcoder.webservice.config.wrapper.MapWrapperFactory;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * mybatis配置類,將自定義的MapWrapperFactory覆蓋默認的ObjectWrapperFactory
 */
@Configuration
public class MybatisConfig {
    private Logger logger = LoggerFactory.getLogger(MybatisConfig.class);
    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer() {
        logger.info("initialize the ConfigurationCustomizer....");
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setObjectWrapperFactory(new MapWrapperFactory());
            }
        };
    }
}

config/RedisConfig

package com.mrcoder.webservice.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mrcoder.mrutils.redis.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
 * @redis 配置類
 */
@Configuration
public class RedisConfig {
    private Logger logger = LoggerFactory.getLogger(RedisConfig.class);
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置連接工廠
        template.setConnectionFactory(factory);

        //使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值(默認使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        // 指定要序列化的域追迟,field,get和set,以及修飾符范圍溶其,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化輸入的類型,類必須是非final修飾的敦间,final修飾的類瓶逃,比如String,Integer等會跑出異常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);
        // 值采用json序列化
        template.setValueSerializer(jacksonSeial);
        //使用StringRedisSerializer來序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 設置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        template.afterPropertiesSet();
        return template;
    }
    /**
     * 對hash類型的數(shù)據(jù)操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForHash();
    }
    /**
     * 對redis字符串類型數(shù)據(jù)操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ValueOperations<String, Object> valueOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForValue();
    }
    /**
     * 對鏈表類型的數(shù)據(jù)操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForList();
    }
    /**
     * 對無序集合類型的數(shù)據(jù)操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForSet();
    }
    /**
     * 對有序集合類型的數(shù)據(jù)操作
     *
     * @param redisTemplate
     * @return
     */
    @Bean
    public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) {
        return redisTemplate.opsForZSet();
    }
    /**
     * 使用上面初始化的RedisTemplate實例來初始化一個RedisUtil對象
     * ps:@Qualifier("redisTemplate") 可以不用加束铭,如果存在RedisTemplate實例,spring會默認注入
     */
    @Bean
    public RedisUtil redisUtil(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        RedisUtil redisUtil = new RedisUtil();
        redisUtil.setRedisTemplate(redisTemplate);
        return redisUtil;
    }
}

config/Swagger2Config

package com.mrcoder.webservice.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
 * @Description: swagger2配置類
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.mrcoder.webservice.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("SPRING-BOOT整合MYBATIS--API說明文檔")
                .description("2019-04-26")
                .version("1.0.0")
                .license("署名-MrCoder")
                .build();
    }
}

controller/TestController

package com.mrcoder.webservice.controller;
import com.mrcoder.mrentity.entity.master.Student;
import com.mrcoder.mrservice.RedisService;
import com.mrcoder.mrservice.StudentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@Api(value = "Test", description = "Test測試Controller")
public class TestController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private RedisService redisService;
    private Log logger = LogFactory.getLog(getClass());
    @ApiOperation(value = "log測試接口", notes = "測試寫level日志")
    @RequestMapping("log")
    public void testAll() {
        logger.info("====info");
        logger.warn("====warn");
        logger.error("====error");
    }
    //列表查詢
    @RequestMapping("getStudentList")
    public ResponseEntity<List<Student>> getStudentList() {
        return ResponseEntity.ok(studentService.getList());
    }
    //列表查詢
    @RequestMapping("getStudentListByAnno")
    public ResponseEntity<List<Student>> getStudentListByAnno() {
        return ResponseEntity.ok(studentService.getListByAnno());
    }
    //新增
    @RequestMapping("addStudent")
    public int addStudent() {
        Student student = new Student();
        student.setAge(1);
        student.setGrade(1);
        student.setName("student");
        return studentService.save(student);
    }
    //更新
    @RequestMapping("updateStudent/{id}")
    public int updateStudent(@PathVariable(name = "id") Long id) {
        Student student = new Student();
        student.setAge(10);
        student.setGrade(10);
        student.setName("update");
        student.setId(id);
        return studentService.update(student);
    }
    //刪除
    @RequestMapping("deleteStudent/{id}")
    public int deleteStudent(@PathVariable(name = "id") Long id) {
        return studentService.delete(id);
    }
    //事務
    @RequestMapping("transSuccess")
    public void transSuccess() {
        //人為制造0除異常測試事務分布式事務回滾
        studentService.trans(1);
    }
    //事務
    @RequestMapping("transRoll")
    public void transRoll() {
        //人為制造0除異常測試事務分布式事務回滾
        studentService.trans(0);
    }
    //redis string讀寫
    @RequestMapping(value = "/redis")
    public String redis() {
        redisService.setValue("test", "test123");
        return redisService.getValue("test").toString();
    }
}

WebServiceApplication

package com.mrcoder.webservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.mrcoder"})
public class WebServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(WebServiceApplication.class, args);
    }
}

注意

@ComponentScan(basePackages = {"com.mrcoder"})

這個注解是用來掃描com.mrcoder下的所有類的厢绝。

核心配置,主要的數(shù)據(jù)源配置都在此
resources/application.yml

## 公共配置start
## 配置數(shù)據(jù)源相關信息
spring:
  ## 環(huán)境配置
  profiles:
    active: dev
  ## 數(shù)據(jù)源設置
  datasource:
    type: com.alibaba.druid.pool.xa.DruidXADataSource
    druid:
      ## 連接池配置
      master:
        ## JDBC配置
        name: master
        url: jdbc:mysql://192.168.145.131:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: true
        testOnReturn: true
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
      slave:
        ## JDBC配置
        name: slave
        url: jdbc:mysql://192.168.145.131:3306/test2?useUnicode=true&characterEncoding=UTF-8&useSSL=false&autoReconnect=true&failOverReadOnly=false&serverTimezone=GMT%2B8
        username: root
        password: 123456
        driver-class-name: com.mysql.cj.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: true
        testOnReturn: true
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20

  redis:
    host: 127.0.0.1  # redis服務所在的地址
    port: 6379
    password:   # redis的密碼默認為空
    pool:
      max-active: 8  #連接池最大連接數(shù)(使用負值表示沒有限制)
      max-idle: 8  #連接池最大空閑數(shù)
      min-idle: 1  #連接池最小空閑數(shù)
      max-wait: 60000  #獲取連接的超時等待事件
    timeout: 30000  #連接redis服務器的最大等待時間

  #druid監(jiān)控頁面用戶名和密碼
  druid:
    name: admin
    pass: admin


## 該配置節(jié)點為獨立的節(jié)點
mybatis:
  mapper-locations: classpath:mapper/*/*.xml  # 注意:一定要對應mapper映射xml文件的所在路徑
  type-aliases-package: com.mrcoder.mrentity.entity # 注意:對應實體類的路徑
  configuration:
    map-underscore-to-camel-case: true

## 公共配置 end


---
## 開發(fā)環(huán)境配置
spring:
  profiles: dev
server:
  port: 8080

---
## 測試環(huán)境配置
spring:
  profiles: test
server:
  port: 8082

---
## 生產環(huán)境配置
spring:
  profiles: prod
server:
  port: 8084

這邊細心的盆友發(fā)現(xiàn)了


17.png

這邊是為了區(qū)分多個環(huán)境的配置契沫,實際項目開發(fā)時,都會區(qū)分開發(fā)/聯(lián)調/測試/生產等環(huán)境昔汉,yml配置文件本身支持多環(huán)境的區(qū)分懈万,用“---”隔開來不同環(huán)境。

公用的配置寫在最上方即可靶病,需要采用的配置用"active"關鍵詞聲明即可会通。


18.png

atomikos分布式事務管理器配置
resources/jta.properties

com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory
com.atomikos.icatch.max_timeout=600000
com.atomikos.icatch.default_jta_timeout=600000
com.atomikos.icatch.log_base_dir =transaction-logs
com.atomikos.icatch.log_base_name=springboot-mybatis
com.atomikos.icatch.serial_jta_transactions=false

日志配置
resources/logback-spring.xml

<configuration debug="false" scan="true" scanPeriod="10 seconds">
    <contextName>logback</contextName>
    <!--輸出sql語句-->
    <logger name="com.mrcoder.webservice" level="debug"/>
    <property name="path" value="/logs"></property>
    <property name="maxHistory" value="30"/>
    <property name="maxFileSize" value="50MB"/>
    <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>debug</level>
        </filter>
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
    </appender>
    <appender name="debug_file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/logback_debug.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 每天一歸檔 -->
            <fileNamePattern>${path}/logback_debug.log.%d{yyyy-MM-dd}-%i.zip</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>DEBUG</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <appender name="info_file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/logback_info.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 每天一歸檔 -->
            <fileNamePattern>${path}/logback_info.log.%d{yyyy-MM-dd}-%i.zip</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>INFO</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <appender name="warn_file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/logback_warn.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 每天一歸檔 -->
            <fileNamePattern>${path}/logback_warn.log.%d{yyyy-MM-dd}-%i.zip</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>WARN</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <appender name="error_file" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>logs/logback_error.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 每天一歸檔 -->
            <fileNamePattern>${path}/logback_error.log.%d{yyyy-MM-dd}-%i.zip</fileNamePattern>
            <maxHistory>${maxHistory}</maxHistory>
            <timeBasedFileNamingAndTriggeringPolicy
                    class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>${maxFileSize}</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%date %level [%thread] %logger{36} [%file : %line] %msg%n
            </pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>ERROR</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
    <root>
        <level value="info"/>
        <appender-ref ref="console"/>
        <appender-ref ref="debug_file"/>
        <appender-ref ref="info_file"/>
        <appender-ref ref="warn_file"/>
        <appender-ref ref="error_file"/>
    </root>
</configuration>

至此,所有的代碼均已完善娄周,大家已經可以運行


19.png

運行

http://localhost:8080/log
http://localhost:8080/getStudentList
http://localhost:8080/getStudentListByAnno
http://localhost:8080/addStudent
http://localhost:8080/updateStudent/1
http://localhost:8080/deleteStudent/1
http://localhost:8080/transSuccess
http://localhost:8080/transRoll
http://localhost:8080/redis

關于druid和swagger2的使用

druid監(jiān)控 (具體使用請查看官方文檔)
http://localhost:8080/druid 賬號和密碼在application.yml有配置

20.png

swagger2 api文檔 (具體使用請查看官方文檔)
http://localhost:8080/swagger-ui.html
關于swagger2 api文檔的自動生成涕侈,我們只是簡單的測試了一下

21.png

關于mybatis 代碼自動生成

這個其實在前幾章,作者已經介紹過了煤辨,但是這邊再講一下裳涛。
我們看mr-entity子模塊的pom.xml文件,可以看到注釋的build信息众辨,只需放開注釋端三,我們假設在你的master數(shù)據(jù)源(也就是test庫)中有張person表,你想自動生成entity和mapper文件鹃彻,只需修改resources/generator/masterGenerator.xml


22.png

然后點擊IDEA右側


23.png

關于打包的介紹

關于打包的幾個pom.xml build塊配置
先看父模塊pom.xml中的


24.png

這個是跑測試用例JUnit的配置

再看web-service子模塊的pom.xml配置


25.png

重要的掉已經在截圖中標紅了郊闯,大家可以重點看下~

最后,我們再看mr-entity子模塊pom.xml中的build信息


26.png

可以看到浮声,這邊是注釋的虚婿,為啥注釋呢?因為像mr-entity泳挥,mr-service然痊,mr-utils等模塊無需打包,我們最終需要打包的只有真正的應用web-service模塊屉符。也就是說只有需要打包的模塊才能有build配置信息剧浸。

最后,打包命令我們只需在IDEA右側點擊


27.png

注意矗钟,作者打包時操作的是root項目唆香,也就是父項目。操作父項目執(zhí)行的操作會對所有的子模塊執(zhí)行吨艇,若同學們只想打包某個子項目只需對對應的子模塊下執(zhí)行操作即可~
強調一下重點躬它,先clean,再package东涡!

執(zhí)行完成后冯吓,我們看IDEA的console口出現(xiàn)


28.png

此時倘待,我們發(fā)現(xiàn),各個模塊下都會出現(xiàn)一個target文件夾组贺,且里面會有對應的jar包凸舵,我們找到web-service服務模塊的jar包(為什么找這個,因為只有它才是真正提供服務的模塊失尖,才有入口啟動類啊奄,通俗點,只有它能運行掀潮,不懂的可以再回頭看看文章菇夸。)
我們再cmd下執(zhí)行 jar -jar xxxx.jar包 即可運行該服務!linux下同理仪吧!注意峻仇,必須按照JDK環(huán)境,這里就不講如何安裝配置JDK了邑商。

總結

好了,至此凡蚜,一個可生產的springboot項目結構已經搭建完畢人断,該結構可以直接拿去投產,從結構的構思到demo的編寫朝蜘,作者花了幾天的時間恶迈,還請用的上的同學關注下作者的公眾號,同時對github點個贊~

項目地址

https://github.com/MrCoderStack/SpringBootFrame

請關注我的訂閱號

訂閱號.png
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末谱醇,一起剝皮案震驚了整個濱河市暇仲,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌副渴,老刑警劉巖奈附,帶你破解...
    沈念sama閱讀 221,331評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異煮剧,居然都是意外死亡斥滤,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,372評論 3 398
  • 文/潘曉璐 我一進店門勉盅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來佑颇,“玉大人,你說我怎么就攤上這事草娜√粜兀” “怎么了?”我有些...
    開封第一講書人閱讀 167,755評論 0 360
  • 文/不壞的土叔 我叫張陵宰闰,是天一觀的道長茬贵。 經常有香客問我簿透,道長,這世上最難降的妖魔是什么闷沥? 我笑而不...
    開封第一講書人閱讀 59,528評論 1 296
  • 正文 為了忘掉前任萎战,我火速辦了婚禮,結果婚禮上舆逃,老公的妹妹穿的比我還像新娘蚂维。我一直安慰自己,他們只是感情好路狮,可當我...
    茶點故事閱讀 68,526評論 6 397
  • 文/花漫 我一把揭開白布虫啥。 她就那樣靜靜地躺著,像睡著了一般奄妨。 火紅的嫁衣襯著肌膚如雪涂籽。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,166評論 1 308
  • 那天砸抛,我揣著相機與錄音评雌,去河邊找鬼。 笑死直焙,一個胖子當著我的面吹牛景东,可吹牛的內容都是我干的。 我是一名探鬼主播奔誓,決...
    沈念sama閱讀 40,768評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼斤吐,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了厨喂?” 一聲冷哼從身側響起和措,我...
    開封第一講書人閱讀 39,664評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蜕煌,沒想到半個月后派阱,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 46,205評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡幌绍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,290評論 3 340
  • 正文 我和宋清朗相戀三年颁褂,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片傀广。...
    茶點故事閱讀 40,435評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡颁独,死狀恐怖,靈堂內的尸體忽然破棺而出伪冰,到底是詐尸還是另有隱情誓酒,我是刑警寧澤,帶...
    沈念sama閱讀 36,126評論 5 349
  • 正文 年R本政府宣布,位于F島的核電站靠柑,受9級特大地震影響寨辩,放射性物質發(fā)生泄漏。R本人自食惡果不足惜歼冰,卻給世界環(huán)境...
    茶點故事閱讀 41,804評論 3 333
  • 文/蒙蒙 一靡狞、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧隔嫡,春花似錦甸怕、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,276評論 0 23
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至秸滴,卻和暖如春武契,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背荡含。 一陣腳步聲響...
    開封第一講書人閱讀 33,393評論 1 272
  • 我被黑心中介騙來泰國打工咒唆, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人释液。 一個月前我還...
    沈念sama閱讀 48,818評論 3 376
  • 正文 我出身青樓钧排,卻偏偏與公主長得像,于是被迫代替她去往敵國和親均澳。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,442評論 2 359

推薦閱讀更多精彩內容