SpringBoot学习笔记(一)

1、Spring的优缺点

1.1 优点

(1)开源,轻量级,非侵入式的一站式框架,简化企业级应用开发。

(2)控制反转(IOC),依赖注入(DI)降低了组件之间的耦合性,实现了软件各层之间的解耦。

(3)面向切面(AOP),利用它可以很容易实现一些拦截,如事务控制等。

(4)spring对于主流的应用框架提供了很好的支持,例如mybatis。

(5)spring提供有自己的mvc实现。

1.2 缺点

虽然Spring的组件代码是轻量级的,但它的配置却是重量级的。虽然spring引入了注解功能,但是仍然需要编写大量的模板化配置文件.

项目的jar依赖管理也是一件耗时耗力的事情,在环境搭建时,需要分析要导入哪些库的坐标,而且还需要分析导入与之有依赖关系的其他库的坐标,一旦选错依赖的版本,随之而来的不兼容问题就会严重阻碍项目的开发进度。

1.3 SpringBoot解决问题

SpringBoot对上述Spring的缺点进行的改善和优化,基于约定优于配置的思想.可以让开发人员不必在配置与逻辑业务之间进行思维的切换,全身心的投入到逻辑业务的代码编写中,从而大大提高了开发的效率,一定程度上缩短了项目周期。

2、SpringBoot的概述

2.1 概述

Spring Boot是由Pivotal团队提供的在spring框架基础之上二次开发的框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。

该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域成为领导者。

Spring Boot就是对各种框架的整合,让他们集成在一起更加简单,它做了那些没有它你自己也会去做的Spring Bean配置。你不用再写这些样板配置了,可以专注于应用程序的逻辑.

Spring Boot你只需要“run”就可以非常轻易的构建独立的、生产级别的spring应用。

我们为spring平台和第三方依赖库提供了一种固定化的使用方式,使你能非常轻松的开始开发你的应用程序。大部分Spring Boot应用只需要很少的配置。

2.2 SpringBoot的特点

(1)创建独立的spring应用程序

(2)直接内嵌tomcat、jetty和undertow(不需要打包成war包部署)

(3)提供了固定化的“starter”配置,以简化构建配置

(4)尽可能的自动配置spring和第三方库

(5)提供产品级的功能,如:安全指标、运行状况监测和外部化配置等

(6)绝对不会生成代码,并且不需要XML配置

2.3 SpringBoot的核心功能

起步依赖

起步依赖就是将具备某种功能的坐标打包到一起,并提供一些默认的功能。

自动配置

Spring Boot的自动配置是一个运行时(更准确地说,是应用程序启动时)的过程,考虑了众多因素,才决定Spring配置应该用哪个,不该用哪个。该过程是Spring自动完成的。

3、搭建SpringBoot环境

(1)Maven 下载 SpringBoot 依赖的jar包


    
        org.springframework.boot
        spring-boot-starter-web
        2.2.2.RELEASE
    


    
        org.springframework.boot
        spring-boot-starter-tomcat
        2.2.2.RELEASE
    

(2)编写入口程序main函数

SpringBoot 通过java的注解的形式启动,就像javaSE程序一样,通过main函数入口。

package com.homyit.springboot03;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Springboot03Application {
    public static void main(String[] args) {
        SpringApplication.run(Springboot03Application.class, args);
    }
}

(3)编写配置文件 application.yml

#内置服务器的配置
server:
  port: 8080

#spring的配置(配置spring视图解析器和数据源配置)
spring:
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/shop?characterEncoding=utf-8&serverTimezone=GMT
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    platform: mysql
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20

(4)配置springboot热部署


    org.springframework.boot
    spring-boot-devtools
    2.2.2.RELEASE

以后修改代码之后就不用每次执行main函数启动工程.

(5)配置SpringBoot支持jsp


    org.apache.tomcat.embed
    tomcat-embed-jasper
    9.0.22

配置视图解析器

spring:
  mvc:
    view:
      prefix: /WEB-INF/jsp/
      suffix: .jsp

(6)SpringBoot集成JDBC

导入jdbc包


    
      org.springframework.boot
      spring-boot-starter-jdbc
      2.2.2.RELEASE
    

导入mysql驱动包


    
      mysql
      mysql-connector-java
      8.0.20
    

(7)配置数据源信息

导入阿里数据源


    
      com.alibaba
      druid
      1.1.10
    

在yml文件注册阿里数据库连接池

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/shop?characterEncoding=utf-8&serverTimezone=GMT
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    platform: mysql
    type: com.alibaba.druid.pool.DruidDataSource
    initialSize: 5
    minIdle: 5
    maxActive: 20

(8)编写配置Druid的监控

DruidDataSourceConfig.java

package com.homyit.springBootPro.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
//spring自动扫描加载此类
@Configuration
public class DruidDataSourceConfig {

        @Bean
        @ConfigurationProperties(prefix = "spring.datasource")
        public DataSource druid() {
            return new DruidDataSource();
        }

        // 配置Druid的监控
        // 1、配置一个管理后台的Servlet
        @Bean
        public ServletRegistrationBean statViewServlet() {
            ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

            Map initParams = new HashMap();
            // 监控页面登录用户名     
            initParams.put("loginUsername", "admin");

            // 监控页面登录用户密码
            initParams.put("loginPassword", "123456");

            // ip白名单(没有配置或者为空,则允许所有访问)
            initParams.put("allow", "");

            // ip黑名单(如果某个ip同时存在,deny优先于allow)
            initParams.put("deny", "");
            bean.setInitParameters(initParams);
            return bean;
        }

        // 2、配置一个web监控的filter
        @Bean
        public FilterRegistrationBean webStatFilter() {
            FilterRegistrationBean bean = new FilterRegistrationBean();
            bean.setFilter(new WebStatFilter());

            Map initParams = new HashMap();

            // 不拦截的静态资源
            initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
            bean.setInitParameters(initParams);

            // 拦截所有的请求
            bean.setUrlPatterns(Arrays.asList("/*"));
            return bean;
        }
}

(9)集成Mybatis

导入springboot集成mybatis环境的jar包


        org.mybatis.spring.boot
        mybatis-spring-boot-starter
        2.1.1

在application.yml中配置mybatis信息

mybatis:
  mapper-locations: classpath:mapper/*Mapper.xml             #映射文件
  type-aliases-package: com.homyit.springBootPro.bean       #别名
  configuration:
    cache-enabled: true                                        #二级缓存
    map-underscore-to-camel-case: true                         #java驼峰与数据库下划线对应转换

application.yml中配置控制台输出sql脚本

# 配置控制台输出sql脚本
logging:
  level:
    com:
      homyit:
        springBootPro:
          dao: TRACE

在Springboot03Application.java主函数类的上面添加扫描mapper文件注解

package com.homyit.springboot03;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.homyit.springboot03.mapper")
public class Springboot03Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot03Application.class, args);
    }
}

(10)配置文件上传

导入配置文件上传jar包


        
            commons-fileupload
            commons-fileupload
            1.3.3
        

编写文件上传配置类

package com.homyit.springboot03.util;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

@Configuration
public class MultipartConfig {

    /**
     * 文件上传配置
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartConfigElement() {
        CommonsMultipartResolver multipartresolver = new CommonsMultipartResolver();
        multipartresolver.setMaxUploadSize(1024*1024*5);
        multipartresolver.setDefaultEncoding("utf-8");
        return multipartresolver;
    }
}

(11)配置自定义拦截器

编写拦截器类

package com.homyit.springboot03.util;

import com.homyit.springboot03.bean.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    /*
        方法:检测用户是否登录,若没有登录则跳转登录页
        当请求到达控制器之前被执行
       true--继续向下执行,到达下一个拦截器,或控制器
       false--不会继续向下执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user == null){
            response.sendRedirect(request.getContextPath()+"/demoCtl/toLogin");
            return false;
        }else{
            return true;
        }
    }

    /*
    控制器方法执行之后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /*
    整个请求结束后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

配置自定义拦截器

package com.homyit.springboot03.util;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 注册自定义拦截器
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer{

    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration inter =  registry.addInterceptor(new LoginInterceptor());
                inter.addPathPatterns("/**");                   //拦截的路径
                inter.excludePathPatterns("/demoCtl/toLogin");  //放行的路径
    }
}

你可能感兴趣的:(javaee)