SpringBoot

SpringBoot

作用:整合了流行的第三方的框架,简化项目搭建操作,快速搭建spring应用

先描述一下一些区别于SpringMVC的注解

注解意义
@RestContrller视图解析器失效,不会跳转页面,return “abv”,就是返回abv
@GetMapping@RequestMapping(method = RequestMethod.GET)的缩写
@Configuration标识配置类的注解
@Bean配置bean的注解,搭配@configuration使用
@EnableScheduling开启之后默认添加到springBoot中,启动就会开始执行
@Scheduled定时器的注解
@Mapper单个mapper.xml的扫描(使用在mapper.xml中)
@MapperScan扫描mapper.xml的路径,用在SpringBoot启动类
热部署

需要依赖和在spring-boot-maven-plugin配置fork

 
 <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        
 <configuration>
<!--热部署需要的配置-->
<fork>true</fork>
</configuration>

在这里插入图片描述

配置启动类

自动扫spring包

@ComponentScan(basePackages = {"com"})
配置过滤器
  @Bean
    public FilterRegistrationBean<Filter> registFilter(){
        FilterRegistrationBean<Filter> filterFilterRegistrationBean = new FilterRegistrationBean<>();
        filterFilterRegistrationBean.setName("MyFlter");
        filterFilterRegistrationBean.setFilter(new Filter() {
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {

            }

            @Override
            public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                System.out.println("过滤前!");
                filterChain.doFilter(servletRequest, servletResponse);
                System.out.println("过滤之后!");
            }

            @Override
            public void destroy() {

            }
        });
        filterFilterRegistrationBean.addUrlPatterns("/*");
        return filterFilterRegistrationBean;


    }
自定义配置类

务必使用@configuration注解,可以把bean用@bean加载进该类,不使用@configuration就只能写进启动类

@Configuration
public class Config {
	@bean
	public void test(){
	}
}

这里就不得不提到@configuration和@component的区别和联系了

从定义来看, @Configuration 注解本质上还是 @Component,因此 <context:component-scan/> 或者 @ComponentScan 都能处理@Configuration 注解的类。

自定义配置

语法:value(${config})

#applicatino.properties
server.port=8082
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

my.name=wei
public class Config {
    @Value("${my.name}")
    private String name;
    
    public void printName(){
        System.out.println(name);
       //输出:wei
    }
}
yml配置

具有比properties更格式更美观的格式

允许

server:
  port: 8082

spring:
  mvc:
   view:
    prefix: /
    suffix: jsp
my:
  name: wei
1.配置多套yml配置文件
#将会匹配后缀为test的配置文件为启用状态
profiles:
    active: test
定时任务
1.传统的定时任务(java.util)
@RequestMapping("/quart")
    public void quart() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("定时任务体" + new Date());
            }
        },0,2000);
        //后面两个参数的意思:多久之后执行,
        //比如String s = "2018-10-29" new simpleDateFormat().format("yyyy-MM-dd")
        //重复执行的间隔时间
    }

2.SpringBoot提供的定时任务(@Scheduled)
 /*sprignBoot定时任务(2秒执行一次)*/
    @RequestMapping("/sbQuart")
    @Scheduled(fixedRate = 2000)
    public void taskTest() {
        System.out.println("定时任务已经执行!"+new Date());
    }

   //同时在类上方要加入@EnableScheduling注解,定时器才会执行
定时器配置值意义
fixedRate多久之后开始执行
cron执行的cron表达式

在这里插入图片描述

cron表达式在线生成器

在这里插入图片描述

整合Mybatis
1.导入依赖
<--该依赖不是parent工程中的,所以需要制定version版本--> 
<dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>1.3.0</version>
 </dependency>

该jar包具备了以下几个jar包(所以无需额外导入mybatis_spring,mybatis)

在这里插入图片描述

2.配置mybatis 的 yml
  1. 配置数据源

     datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://172.16.1.255:3306/linayi?autoReconnect=true
        #这里千万不要写成 data-username: 
        username: dev_ess
        password: dev_ess
    
    1. 配置mapper映射和bo类映射以及dao扫包
    mybatis:
      mapper-locations: classpath:com/wei/mapper/*.xml
      type-aliases-package: classpath:com.wei.bo
    

    注意这里dao扫包有两种方式,类似于config扫包,

    • 从启动类加上@MapperScan(basePackages = {"com.wei.dao"})

    • 从每个userDao类上加上@Mapper

log4j打印sql

SpringBoot集成了log4j

在这里插入图片描述

1.使用方法:

application.yml中添加

mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

格式化之后

mybatis:
 configuration:
  log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
异常类处理

对程序发生某一特定定义的异常的时候

做出相应的反应(跳转页面,返回提示)

关键优点:将 Controller 层的异常和数据校验的异常进行统一处理,减少模板代码,减少编码量,提升扩展性和可维护性。

1.处理类上面加上@ControllerAdvice标志其是异常处理类
2.加上@ResponseBody标志其返回json数据
3.定义异常处理方法
//ExceptionHandler标记受处理的异常类,如果不加参数表示拦截所有未标记的异常  
@ExceptionHandler(ArithmeticException.class)
    public UserBO doHandleError() {
        UserBO userBO = new UserBO();
        userBO.setName("请不要除1");
        return userBO;
    }

结果

在这里插入图片描述

集成模板引擎thymeleaf
1.引入依赖
 <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>2.0.5.RELEASE</version>
        </dependency>
    </dependencies>
2.yml引入配置
 thymeleaf:
    cache: false
    prefix: classpath:/templates/
3.添加接口
@RequestMapping("/thymeleaf")
    public String thymeleaf(Model model) {
        model.addAttribute("name", "hu");
        model.addAttribute("age", "16");
        return "HelloThymeleaf";
    }
4.填写页面
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all"
          href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
</head>

<body>

<p th:text="sadf">Welcome to our grocery store!</p>

</body>

</html>

在这里插入图片描述

5.thymelead字符拼接
  • 用||包含
th:text="|中文名:${name}|"
  • 用’’+拼接
th:text="'中文名:'+${name}"
6.thymelead条件判断
<a th:if="${age>=18}">成年</a>
<a th:if="${age<18}">未成年</a>
<!--unless就是否的意思,代表相反-->
<a th:unless="${age>=18}">未成年</a>
7.thymelead循环结构
<a th:each="str,strState : ${eachStr}">
    <!--获取迭代的变量-->
	<a th:text="${str}"></a>
	<!--获取迭代的变量-->
    <a th:text="${strState.current }"></a>
	<!--获取迭代的后缀(从0开始)-->
	<a th:text="${strState.index}"></a>
	<!--获取迭代的后缀(从1开始)-->
    <a th:text="${strState.count}"></a>
	<!--获取迭代集合的长度-->
    <a th:text="${strState.size }"></a>
</a>
<a th:text="${#arrays.length(eachStr)}"></a>
8.thymelead格式化
<a th:text="${#dates.format(birthday,'yyyy-MM-dd')}">
部署
1.使用maven插件进行打包成war
2.启动
  • 然后在war包所在的文件夹下输入 java -jar demo-0.0.1-SNAPSHOT.war
3.访问

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值