45Spring生态系统

Spring生态系统

  • Spring容器中引入Bean

  • Spring+MyBatis

  • 模板引擎(后端渲染HTML)

  • 前后端分离

解析Java框架中entity层,mapper层,service层,controller各层作用

Mybatis 加载 Mapper配置的四种方式

项目一般分三层

  • 为了业务逻辑更清晰,让代码更加复用
  • Controller->只做和HTTP相关
  • Service->业务逻辑代码
  • Dao->只做数据库相关

Spring容器中Bean如何配置

引入数据库相关依赖

搜索springboot mybatis starter

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.1</version>
</dependency>

引入h2

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <version>1.4.200</version>
</dependency>

配置application.properties

spring.datasource.url=jdbc:h2:file:E:/git/my-first-spring/target/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=org.h2.Driver
mybatis.config-location=classpath:db/mybatis/config.xml

自动化迁移插件flyway

<plugin>
   <groupId>org.flywaydb</groupId>
   <artifactId>flyway-maven-plugin</artifactId>
   <version>6.3.2</version>
   <configuration>
      <url>jdbc:h2:file:${project.basedir}/target/test</url>
      <user>root</user>
      <password>root</password>
   </configuration>
</plugin>

在resources/db/migration目录下创建初始化数据库的sql文件

如:V1__CreateTables.sql

后端渲染 模板引擎Freemarker

freemarker spring boot starter

Freemarker升级后的坑!

如果你使用的是最新版的Spring Boot (2.2+),默认的Freemarker扩展名变成了ftlh!如果仍然使用ftl会报错404!请千万注意!

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

resources/templates/index.ftlh

<table>
            <tr>
                <th>排行</th>
                <th>名字</th>
                <th>分数</th>
            </tr>

            <#list items as item>
                <tr>
                    <td>${item?index}</td>
                    <td>${item.user.name}</td>
                    <td>${item.score}</td>
                </tr>
            </#list>
        </table>

HelloController.java

@RequestMapping("/")
public ModelAndView index() {
    List<RankItem> items = rankService.getRank();
    HashMap<String, Object> model = new HashMap<>();
    model.put("items", items);
    return new ModelAndView("index", model);
}

「资料来源:饥人谷」

点赞

发表评论

电子邮件地址不会被公开。必填项已用 * 标注