(自用)Java学习-5.9(Thymeleaf,自动装配,自定义启动器 )

发布于:2025-05-13 ⋅ 阅读:(16) ⋅ 点赞:(0)

一、Thymeleaf 模板技术

  1. 片段定义与复用

    <!-- 声明片段 -->
    <div th:fragment="b1">...</div>
    <!-- 插入片段 -->
    <div th:insert="~{bottom :: b1}"></div>  <!-- 追加内容 -->
    <div th:replace="~{bottom :: b2}"></div> <!-- 替换当前标签 -->
    
  2. 内置对象应用

    <!-- 字符串处理 -->
    <span th:text="${#strings.substring(msg,0,3)}"/>
    <!-- 日期格式化 -->
    <td th:text="${#dates.format(user.birthday,'yyyy-MM-dd')}"></td>
    

二、SpringBoot 整合 MyBatis 全流程

  1. 依赖配置

    <!-- MyBatis Starter -->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
    </dependency>
    
  2. YML 核心配置

    mybatis:
      mapper-locations: classpath:/mappers/*.xml
      type-aliases-package: com.zxst.pojo
      configuration:
        map-underscore-to-camel-case: true
    
  3. Mapper 关联查询示例

    @Select("SELECT * FROM employee")
    @Results({
      @Result(property = "dept", column = "dept_id",
              one = @One(select = "com.zxst.mapper.DeptMapper.getInfoById"))
    })
    List<Employee> getEmpInfo();
    

三、CRUD 功能实现

  1. 增删改查实现要点
    • 新增:表单绑定对象参数
      <form th:action="@{/emp/saveEmp}" method="post">
        <input name="ename">...
      </form>
      
    • 更新:数据回显技术
      @GetMapping("/getOneEmpById")
      public String getOneEmpById(Model model, @RequestParam Integer eid) {
        model.addAttribute("one", employeeMapper.getOneById(eid));
        return "edit";
      }
      
    • 删除:参数传递
      <a th:href="@{/emp/deleteEmp(eid=${emp.eid})}">删除</a>
      

四、自动装配原理(重点)

  1. 启动器核心机制

    @SpringBootApplication
    ↓ 包含
    @EnableAutoConfiguration
    ↓ 触发
    META-INF/spring.factories中的自动配置类
    
  2. 自定义启动器开发

    • 步骤 1:定义配置属性类
      @ConfigurationProperties(prefix = "zxst")
      public class ZxstProperties { private String name; }
      
    • 步骤 2:创建自动配置类
      @Configuration
      @EnableConfigurationProperties(ZxstProperties.class)
      public class ZxstAutoConfiguration {
        @Bean
        public ZxstService zxstService() {
          return new ZxstService(properties.getName());
        }
      }
      
    • 步骤 3:注册配置到META-INF/spring.factories

网站公告

今日签到

点亮在社区的每一天
去签到