小Hub领读:
今天开始,接下来十几天,我要从0到1手把手给你们讲解一个完整的博客项目,从搭建基本架构到最后能正常运行。
今天我们先来用Springboot整合一些基本的框架,让首页能运行起来先哈。其中包括整合Mybatis plus、Freemaker、lombok、还有代码生成工具!
项目名称:eblog
项目Git仓库:https://github.com/MarkerHub/eblog(给个star支持哈)
前几篇文章:
1、Github上最值得学习的Springboot开源博客项目!
项目基本架构搭建
以下过程,我们以idea为开发工具,新建一个springboot项目。
开发环境:
idea
jdk 1.8
maven 3.3.9
mysql 5.7
1. 新建springboot项目
打开idea,新建一个project,选择Spring Initializr。project基本信息填写如下:
接下来,我们来选择一下我们需要集成的框架或中间件,就我们现在刚开发阶段,我们选择以下依赖就可以了:
web
Lombok
Devtools
freemaker
Mysql
Redis
当然了,有些依稀需要我们去完成一些配置,比如我们的mysql、redis需要配置连接信息,一般来说springboot有帮我们完成了很多默认配置,只要按照默认配置来,我们都不需要去修改或者写配置,比如freemaker的~
选择好了之后,idea会自动我们添加依赖,打开项目如下:
pom.xml的依赖包如下:
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-freemarker
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-devtools
runtime
mysql
mysql-connector-java
runtime
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
现在,我们去一步步完成框架的集成。
2. 集成lombok
刚才我们已经自动导入了lombok的依赖包
org.projectlombok
lombok
true
如果你使用lombok注解还报错,说明你的idea还没有安装lombok插件,参考一下这个百度百科教程:
IntelliJ IDEA lombok插件的安装和使用(https://jingyan.baidu.com/article/0a52e3f4e53ca1bf63ed725c.html)
安装完毕后重启idea,lombok注解使用就不会再报错了~
3. 集成mybatis plus
步骤1:
首先我们来看下mybatis plus的官网并且找到整合包:https://mp.baomidou.com/guide/install.html
官网中提示springboot的集成包:
com.baomidou
mybatis-plus-boot-starter
3.1.0
把mybatis plus导入pom中。然后在application.yml中写入我们的数据源链接信息:
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/third-homework?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC
username: root
password: admin
mybatis-plus:
mapper-locations: classpath*:/mapper/**Mapper.xml
好了,我们的mybatis plus已经集成成功。
步骤2:
我们借用官网给我们提供的代码生成工具:https://mp.baomidou.com/guide/generator.html
注意MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:
com.baomidou
mybatis-plus-generator
3.1.0
前面我们已经自动引入了freemaker的集成包,所以这里不需要再重复引入freemaker的引擎依赖。接着就是修改我们的代码生成器的相关配置,具体修改如下:
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
package com.example;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
/**
*
* 读取控制台内容
*
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
// gc.setOutputDir("D:\\test");
gc.setAuthor("公众号:java思维导图");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
gc.setServiceName("%sService");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/third-homework?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("admin");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent("com.example");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass("com.example.entity.BaseEntity");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setSuperControllerClass("com.example.controller.BaseController");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setSuperEntityColumns("id", "created", "modified", "status");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
注意安装配置来生成BaseEntity、BaseController、还有包路径相关等东西。
BaseEntity:
@Data
public class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Date created;
private Date modified;
}
BaseController:
public class BaseController {
@Autowired
HttpServletRequest req;
}
代码生成之后,看到resource/mapper这里,我们把这个null去掉。
修改之后结果:
到这里还没完成,注意一下:还需要配置*@MapperScan("com.example.mapper"*)注解。说明mapper的扫描包。
接下来,我们去写一个小小测试,测试一下mybatis plus有没集成成功,能否查到数据了:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ThirdHomeworkApplicationTests {
@Autowired
UserService userService;
@Test
public void contextLoads() {
User user = userService.getById(1L);
System.out.println(user.toString());
}
}
test之后的结果能够查出数据。注意在mysql中添加一条id为1的数据哈。
4. 集成freemaker
前面我们已经自动集成了freemaker的依赖包,现在我们只需要一些简单配置,其实都不需要配置了:可以看到,我们再写配置的时候springboot已经帮我们完成了很多默认配置,修改自己需要修改的就行了。我这里其实不需要修改,后面需要我们再调整。
spring:
freemarker:
cache: false
然后我们现在去定义一下freemaker的模板。不熟悉freemaker标签的同学可以先去熟悉一下:
首先我们定义个全局layout(宏),用于同一所有的页面。
templates/inc/layout.ftl
lang="zh-CN">
charset="utf-8">
name="viewport" content="width=device-width, initial-scale=1.0">
${title?default('java思维导图')}
#macro>
上面我们用了几个标签,下面我简单讲解一下:
定义一个宏(模板),名字是loyout,title是参数
表示在引入loyout这个宏的地方,标签内容的所有内容都会替换到这个标签中。
比如:
首页templates/index.ftl
hello world !!
@layout>
得到的内容其实是:
lang="zh-CN">
charset="utf-8">
name="viewport" content="width=device-width, initial-scale=1.0">
首页
hello world !!
上面我们定义了一个layout宏,这要的好处是一些css、js文件我们直接放到loyout中,然后具体的页面我们直接include,然后在标签内写内容即可。ok,让我们写一个IndexController来跳到这个首页。
@Controller
public class IndexController extends BaseController {
@RequestMapping({"", "/", "/index"})
public String index () {
return "index";
}
}
渲染之后的效果如下:
好了,freemaker可以正常显示页面,现在我们去把我们的博客主题集成进来,我们使用的是layui官方提供的社区模板
https://fly.layui.com/store/FlyTemplate/
先下载下来,解压之后得到:
用idea打开index.html,看下div的层次关系,可以得出以下:
ok,知道了div的层次之后,我们来一一分开来填入内容,该弄成模板的地方就弄成模板,比如头,尾,侧边栏等。我们先把原来的index.html页面的层次分开,分为header.ftl、header-panel.ftl、footer.ftl、right.ftl。然后在layout.ftl中引入我们的js、css文件。得到的结果如下:
templates/inc/layout.ftl
页面分好之后,得到的打开http://localhost:8080,效果如下:
注意:页面中我用到了一个${base}的参数,我是在项目启动时候就初始化的一个项目路径参数,在com.example.config.ContextStartup。大家注意一下。
servletContext.setAttribute("base", servletContext.getContextPath());
结束语
好啦,今天的框架先搭建到这里了哈,后续还有10多篇逐渐发布出来,已经学好了哈。从0到1搭建一个完整的高可用Springboot博客项目,最值得学习的Springboot博客项目。
项目地址:https://github.com/MarkerHub/eblog
写项目写文章都不易,别忘了给个Star哈,感谢支持!
(完)
MarkerHub文章索引:
https://github.com/MarkerHub/JavaIndex
【项目相关文章】
1、Github上最值得学习的Springboot开源博客项目!