Spring Boot一课一得

我们知道,从 2002 年开始,Spring 一直在飞速的发展,如今已经成为了在Java EE(Java Enterprise Edition)开发中真正意义上的标准,但是随着技术的发展,Java EE使用 Spring 逐渐变得笨重起来,大量的 XML 文件存在于项目之中。繁琐的配置,整合第三方框架的配置问题,导致了开发和部署效率的降低。

我认为 Spring 的 Web 应用体系结构可以大大简化,如果它提供了从上到下利用 Spring 组件和配置模型的工具和参考体系结构。在简单的 main()方法引导的 Spring 容器内嵌入和统一这些常用Web 容器服务的配置。

这一要求促使了 2013 年初开始的 Spring Boot 项目的研发,到今天,Spring Boot 的版本已经到了 2.0.3 RELEASE。Spring Boot 并不是用来替代 Spring 的解决方案,而是和 Spring 框架紧密结合用于提升 Spring 开发者体验的工具。

它集成了大量常用的第三方库配置,Spring Boot应用中这些第三方库几乎可以是零配置的开箱即用(out-of-the-box),大部分的 Spring Boot 应用都只需要非常少量的配置代码(基于 Java 的配置),开发者能够更加专注于业务逻辑。

spring boot 的优点:Spring Boot 是伴随着 Spring 4.0 诞生的,从字面理解,Boot是引导的意思,因此 Spring Boot 旨在帮助开发者快速搭建 Spring 框架。Spring Boot 继承了原有 Spring 框架的优秀基因,使 Spring 在使用中更加方便快捷。

一,开发过程中遇到的问题,将解决过程写下来,

  1. 检查测试配置:首先,我检查了测试类的注解配置,确保@Test、@RunWith、@SpringBootTest等注解都已经正确使用。
  2. 检查依赖:检查项目的依赖是否正确,尤其是与Spring Boot测试相关的依赖。
  3. 检查启动类:确认启动类上是否有@SpringBootApplication注解,该注解包含了@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan等注解,确保Spring Boot应用程序能正确启动。
  4. 检查配置文件:检查application.properties或application.yml文件中的配置是否正确。
  5. 检查测试代码:检查测试代码中是否有正确的注入和断言。
  6. 查看日志:查看日志中的详细错误信息,这有助于定位问题所在。

在经过上述步骤后,我发现问题是出在测试代码中的一个类上,这个类使用了@Autowired注解来注入一个接口的实现类,但是该实现类并没有在Spring容器中注册。

解决方案:
在测试代码中,将该实现类的实例化方式改为使用@MockBean来模拟该接口的实现类。这样,Spring容器就会自动注册该实现类,从而解决了“Failed to load ApplicationContext”的问题。

总结:
在开发过程中遇到问题时,要学会如何定位问题并找到解决方案。上述案例中,通过逐一排查和日志分析,我最终找到了问题的根源并解决了它。此外,还需要注意以下几点:

  1. 确保项目的依赖正确且版本兼容。
  2. 在测试代码中使用@MockBean或@SpyBean来模拟依赖,这有助于分离测试代码和实际业务代码。
  3. 在调试时可以使用Spring Boot提供的调试工具来更方便地查看变量值和调用堆栈。
  4. 在开发过程中要保持代码的可读性和可维护性,遵循良好的编码规范。

(2),代码问题:

package com.example.demo_parking.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo_parking.entity.PricingStandard;
import com.example.demo_parking.mapper.PricingStandardMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class PricingStandardService extends ServiceImpl<PricingStandardMapper, PricingStandard> {
    PricingStandardMapper mapper;

    @Autowired
    public PricingStandardService(PricingStandardMapper mapper){
        this.mapper=mapper;
    }

    public List<PricingStandard> getAll() {
        List<PricingStandard> list=mapper.selectList(null);//查询目标,如果有返回值,进行返回,否则返回null值
        return list;
    }

    /*获取所有用户*/
    public PricingStandard getById(Long id) {
        PricingStandard entity=mapper.selectById(id);
        return entity;
    }
    /*插入一行用户数据*/

    public boolean insert(PricingStandard entity) {
        int result=mapper.insert(entity);
        return result>0?true:false;
    }

    /*更新一行用户数据*/
    public boolean update(PricingStandard entity) {
        int result=mapper.updateById(entity);
        return result>0?true:false;
    }


    public boolean delete(Long id) {

        return mapper.deleteById(id)>0?true:false;
    }
}

在导入类时经常导入不了,然后经过仔细的检查才发现是自己的代码有一些是少几个单词的。

package com.example.demo_parking.controller;

import com.example.demo_parking.entity.PricingStandard;


import com.example.demo_parking.service.PricingStandardService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.List;

    @Controller
    @RequestMapping("/pricing")
    public class PricingStandardController {
        PricingStandardService service;
        @Autowired
        public PricingStandardController(PricingStandardService service){
            this.service=service;
        }

        @RequestMapping("/list")
        public String list(Model model){
            List<PricingStandard> entities= service.getAll();
            model.addAttribute("pricingList",entities);
            return "/pricing/list";//此处是对应前段UI对URL
        }
        @RequestMapping(value = "/insert")
        public String insert(Model model){
            //新建user对象,给到UI的model
            model.addAttribute("pricing",new PricingStandard());
            return "/pricing/edit";
        }
        @RequestMapping(value = "/update/{id}")
        public String update(@PathVariable("id") Long id, Model model){
            //根据ID值查找指定的那一行
            PricingStandard entity=service.getById(id);
            //将找到的entity数据传到前端model对象user中
            model.addAttribute("pricing",entity);
            return "/pricing/edit";
        }
        @RequestMapping(value = "/save",method = RequestMethod.POST)
        public String save(@ModelAttribute("pricing") PricingStandard entity){

            boolean result=entity.getId()!=null?service.update(entity):service.insert(entity);
            return  "redirect:/pricing/list";
        }

        @RequestMapping(value = "/detail/{id}")
        public String detail(@PathVariable("id")Long id,Model model){
            PricingStandard entity=service.getById(id);
            model.addAttribute("pricing",entity);
            return "/pricing/detail";
        }

        @RequestMapping(value = "/delete/{id}")
        public String delete(@PathVariable("id")Long id){
            service.delete(id);
            return "redirect:/pricing/list";
        }
    }
server:
  port: 8081 #????9000
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/2022soft1?useUnicode=ture?characterEncoding=UTF-8&useSSL=false
    hikari:
      username: root
      password: 123456
      driver-class-name: com.mysql.cj.jdbc.Driver
  hikari:
    minimum-idle: 5 #??????
    connection-test-query: SELECT 1
    maximum-pool-size: 20 #?????
    auto-commit: true #????
    pool-name: dataHiKariCP #?????
    max-lifetime: 600000 #?????????600000ms=10min
    connection-timeout: 30000 #0.5m
  sql:
    init:
      schema-locations: classpath:db/schema.sql
      mode: always
      continue-on-error: true
      data-locations: classpath:db/data.sql
  thymeleaf:
    cache: false
    prefix: classpath:/templates/
    suffix: .html
    #????????
logging:
  level:
    demo.mybatis: debug
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: true
    use-generated-keys: true

在配置路径时经常配错误,一直发现不出问题之后也是需要老师来帮助才能完成的,然后经过老师的讲解我们才知道以后再遇到这种问题的时候,应该要怎么做的。si

二,Spring boot常用注解介绍:

Spring Boot是一个用于快速、敏捷地开发基于Spring框架的应用的框架,常用注解有:

  1. @SpringBootApplication:该注解是Spring Boot最核心注解,也是组合注解,声明它就可以让Spring Boot自动给程序进行必要的配置(简单的说,开启组件扫描和自己配置的功能)。
  2. @EnableAutoConfiguration:使用该注解作用就是告诉Spring Boot根据添加jar依赖猜测你想如何配置Spring。
  3. @ComponentScan:组件扫描,自动扫面包,并把这些类注册为Bean。
  4. @SpringBootConfiguration:是标志当前的类的配置类。
  5. @Autowired:使用该注解作用就是进行自动注入。
  6. @RestController:此注解就是@Controller和@ResponseBody的集合,使用在controller层的,意思就是告诉控制层里面的方法都是以json的格式进行输出。这些注解在Spring Boot框架中发挥着重要的作用,可以简化开发过程,提高开发效率。

三,.数据层框架的整合和使用,如JdbcTemplate、mybatis、mybatis-plus的原理及其应用实现;

  1. JdbcTemplate:

JdbcTemplate是Spring框架提供的一个模板类,用于简化JDBC数据库操作。它封装了JDBC的调用过程,包括连接数据库、创建statement、处理结果集等。使用JdbcTemplate可以避免直接使用JDBC的繁琐过程,提高开发效率。

原理:JdbcTemplate通过代理方式,封装了JDBC的调用过程。在执行SQL语句时,JdbcTemplate会对结果集进行预处理,将结果集转换为Java对象,并返回给调用者。

应用实现:在Spring配置文件中配置数据源和JdbcTemplate,然后在Java代码中注入JdbcTemplate对象,就可以直接使用它来执行SQL语句。

  1. MyBatis:

MyBatis是一个基于Java的持久层框架,它封装了JDBC的操作过程,让开发者直接编写SQL语句即可完成数据库操作。MyBatis通过XML或注解的方式配置SQL语句,并提供了丰富的映射机制,可以将SQL语句的执行结果映射为Java对象。

原理:MyBatis通过XML或注解的方式配置SQL语句,并使用反射机制执行SQL语句。它支持自定义SQL、存储过程以及高级映射,使得开发者可以更加灵活地操作数据库。

应用实现:在Spring配置文件中配置MyBatis的SqlSessionFactory对象,然后在Java代码中注入SqlSession对象,就可以直接使用它来执行SQL语句。

  1. MyBatis-Plus:

MyBatis-Plus是在MyBatis的基础上进行扩展的一个框架,它提供了更多的便捷功能,如自动映射、分页查询、条件构造器等。MyBatis-Plus的目标是简化MyBatis的使用,提高开发效率。

原理:MyBatis-Plus在MyBatis的基础上添加了一些内置的功能和工具类,如自动映射器、分页插件、条件构造器等。这些功能和工具类简化了MyBatis的使用,让开发者可以更加便捷地操作数据库。

应用实现:在Spring配置文件中配置MyBatis-Plus的SqlSessionFactory对象(或使用内置的SqlSessionFactoryBuilder来创建),然后在Java代码中注入SqlSession对象(或使用内置的SqlSessionTemplate),就可以直接使用它来执行SQL语句。MyBatis-Plus还提供了丰富的Mapper接口和XML映射文件,让开发者可以更加灵活地操作数据库。

四,前端模板引擎Thymeleaf的整合和使用;

Thymeleaf是一个Java模板引擎,可以用于Web和独立环境。它可用于生成HTML,XML,JavaScript,CSS等。以下是Thymeleaf的整合和使用方法:

  1. 引入依赖:在项目的pom.xml文件中添加Thymeleaf的依赖。

  2.  xml


	<dependency> 

	<groupId>org.thymeleaf</groupId> 

	<artifactId>thymeleaf-spring5</artifactId> 

	<version>3.0.11.RELEASE</version> 

	</dependency>
  1. 配置视图解析器:在Spring MVC的配置文件中,配置Thymeleaf的视图解析器。

 

java
@Bean 
public ViewResolver viewResolver() { 
ThymeleafViewResolver resolver = new ThymeleafViewResolver(); 
resolver.setTemplateEngine(templateEngine()); 
resolver.setCharacterEncoding("UTF-8"); 
return resolver; 
} 


@Bean 
public SpringTemplateEngine templateEngine() { 
SpringTemplateEngine engine = new SpringTemplateEngine(); 
engine.setEnableSpringELCompiler(true); 
engine.setTemplateResolver(templateResolver()); 
return engine; 
} 


@Bean 
public ITemplateResolver templateResolver() { 
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(); 
resolver.setPrefix("/WEB-INF/views/"); 
resolver.setSuffix(".html"); 
resolver.setTemplateMode("HTML5"); 
resolver.setCharacterEncoding("UTF-8"); 
return resolver; 
}
  1. 在Controller中返回Thymeleaf模板名称:在Controller的方法中返回Thymeleaf模板的名称,例如:

java
@RequestMapping("/hello") 
public String hello(Model model) { 
model.addAttribute("message", "Hello World!"); 
return "hello"; // 返回模板名称hello.html 
}
  1. 在模板中使用Thymeleaf表达式:在Thymeleaf模板中,可以使用Thymeleaf表达式来访问Controller中添加到Model中的属性。例如:在hello.html模板中,可以使用${message}来访问Controller中添加到Model中的message属性。
  2. 渲染页面:当用户访问Controller中指定的URL时,Thymeleaf会将模板渲染成HTML页面,并发送给用户。用户可以在浏览器中查看渲染后的页面。

五,Bootstrap前端框架的整合及应用;

Bootstrap是一个流行的前端框架,它可以帮助开发者快速构建响应式和移动优先的网站。以下是Bootstrap前端框架的整合及应用:

  1. 下载和安装Bootstrap:可以从官网下载最新版本的Bootstrap,并将其添加到项目中。
  2. 响应式设计:Bootstrap提供了响应式设计的功能,可以根据不同设备的屏幕大小和分辨率来自动调整布局和样式。通过使用响应式设计,可以确保网站在各种设备上都能显示得很好。
  3. 栅格系统:Bootstrap的栅格系统可以帮助开发者快速构建网页布局。通过将页面分成12列的栅格,可以轻松地创建行和列,以及在不同设备上显示不同的布局。
  4. 组件:Bootstrap提供了许多预定义的组件,如导航栏、下拉菜单、轮播图、表格等。这些组件可以帮助开发者快速构建网站的各种功能和界面。
  5. 样式和主题:Bootstrap提供了大量的CSS样式和主题,可以轻松地定制网站的外观和风格。同时,也可以使用自定义的CSS样式和JavaScript脚本,来进一步扩展网站的功能和界面。
  6. 集成jQuery:Bootstrap集成了jQuery库,可以方便地使用jQuery插件来实现各种交互效果。

总之,Bootstrap是一个功能强大的前端框架,可以帮助开发者快速构建响应式、移动优先的网站,并提供了丰富的组件、样式和主题来定制网站的外观和风格。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值