SpringBoot

1. SpringBoot介绍

在这一部分,我们主要了解以下3个问题:

  • 什么是SpringBoot
  • 为什么要学习SpringBoot
  • SpringBoot的特点

1.1 什么是SpringBoot

SpringBoot是Spring项目中的一个子工程,与我们所熟知的Spring-framework 同属于spring的产品:

https://spring.io/projects

我们可以看到下面的一段介绍:

Takes an opinionated view of building production-ready Spring applications. Spring Boot favors convention over configuration and is designed to get you up and running as quickly as possible.

翻译一下:

用一些固定的方式来构建生产级别的spring应用。Spring Boot 推崇约定大于配置的方式以便于你能够尽可能快速的启动并运行程序。

其实人们把Spring Boot 称为搭建程序的脚手架。其最主要作用就是帮我们快速的构建庞大的spring项目,并且尽可能的减少一切xml配置,做到开箱即用,迅速上手,让我们关注与业务而非配置。

1.2 为什么要学习SpringBoot

java一直被人诟病的一点就是臃肿、麻烦。当我们还在辛苦的搭建项目时,可能Python程序员已经把功能写好了,究其原因注意是两点:

  • 复杂的配置

    项目各种配置其实是开发时的损耗, 因为在思考 Spring 特性配置和解决业务问题之间需要进行思维切换,所以写配置挤占了写应用程序逻辑的时间。

  • 一个是混乱的依赖管理

    项目的依赖管理也是件吃力不讨好的事情。决定项目里要用哪些库就已经够让人头痛的了,你还要知道这些库的哪个版本和其他库不会有冲突,这难题实在太棘手。并且,依赖管理也是一种损耗,添加依赖不是写应用程序代码。一旦选错了依赖的版本,随之而来的不兼容问题毫无疑问会是生产力杀手。

而SpringBoot让这一切成为过去!

Spring Boot 简化了基于Spring的应用开发,只需要“run”就能创建一个独立的、生产级别的Spring应用。Spring Boot为Spring平台及第三方库提供开箱即用的设置(提供默认设置,存放默认配置的包就是启动器),这样我们就可以简单的开始。多数Spring Boot应用只需要很少的Spring配置。

我们可以使用SpringBoot创建java应用,并使用java –jar 启动它,就能得到一个生产级别的web工程。

1.3 SpringBoot的特点

Spring Boot 主要目标是:

  • 为所有 Spring 的开发者提供一个非常快速的、广泛接受的入门体验
  • 开箱即用(启动器starter-其实就是SpringBoot提供的一个jar包),但通过自己设置参数(.properties),即可快速摆脱这种方式。
  • 提供了一些大型项目中常见的非功能性特性,如内嵌服务器、安全、指标,健康检测、外部化配置等
  • 绝对没有代码生成,也无需 XML 配置。

更多细节,大家可以到官网查看。

2. 快速入门

接下来,我们就来利用SpringBoot搭建一个web工程,体会一下SpringBoot的魅力所在!

2.1 创建maven项目

创建普通的maven项目即可

2.2 添加依赖

看到这里很多同学会有疑惑,前面说传统开发的问题之一就是依赖管理混乱,怎么这里我们还需要管理依赖呢?难道SpringBoot不帮我们管理吗?

别着急,现在我们的项目与SpringBoot还没有什么关联。SpringBoot提供了一个名为spring-boot-starter-parent的工程,里面已经对各种常用依赖(并非全部)的版本进行了管理,我们的项目需要以这个项目为父工程,这样我们就不用操心依赖的版本问题了,需要什么依赖,直接引入坐标即可!

2.2.1.添加父工程坐标

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>

2.2.2.添加web启动器

为了让SpringBoot帮我们完成各种自动配置,我们必须引入SpringBoot提供的自动配置依赖,我们称为启动器。因为我们是web项目,这里我们引入web启动器:

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

需要注意的是,我们并没有在这里指定版本信息。因为SpringBoot的父工程已经对版本进行了管理了。

这个时候,我们会发现项目中多出了大量的依赖:

这些都是SpringBoot根据spring-boot-starter-web这个依赖自动引入的,而且所有的版本都已经管理好,不会出现冲突。

2.2.3.管理jdk版本

默认情况下,maven工程的jdk版本是1.5,而我们开发使用的是1.8,因此这里我们需要修改jdk版本,只需要简单的添加以下属性即可:

<properties>
    <java.version>1.8</java.version>
</properties>

2.2.4.完整pom

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
</parent>

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

2.3 启动类

Spring Boot项目通过main函数即可启动,我们需要创建一个启动类 Application.java

然后编写main函数:

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

2.4 编写Service

@Service
public class UserService {
    public User findById(Integer id){
        User user = new User();
        user.setId(id);
        user.setName("tom");
        user.setPassword("123456");
        return user;
    }
}

2.5 编写controller

接下来,我们就可以像以前那样开发SpringMVC的项目了!

我们编写一个controller:

controller包必须和Application.java文件同级

代码:

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/find")
    public User find(Integer id){
        User user = userService.findById(id);
        return user;
    }
}

2.6 启动测试

接下来,我们运行main函数,查看控制台,可以看到以下信息:

  • 1)监听的端口是8080
  • 2)SpringMVC的映射路径是:/user
  • 3)/find路径已经映射到了UserController中的find()方法

打开页面访问:http://localhost:8080/user/find?id=1

3. Java配置

在入门案例中,我们没有任何的配置,就可以实现一个SpringMVC+Spring的项目了,快速、高效!

但是有同学会有疑问,如果没有任何的xml,那么我们如果要配置一个Bean该怎么办?比如我们要配置一个数据库连接池,以前会这么玩:

<context:property-placeholder location="classpath:jdbc.properties"/><!-- 加载配置文件 -->  
<!-- 配置连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
      init-method="init" destroy-method="close">
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

现在该怎么做呢?

3.1 回顾历史

事实上,在Spring3.0开始,Spring官方就已经开始推荐使用java配置来代替传统的xml配置了,我们不妨来回顾一下Spring的历史:

  • Spring1.0时代

    在此时因为jdk1.5刚刚出来,注解开发并未盛行,因此一切Spring配置都是xml格式,想象一下所有的bean都用xml配置,细思极恐啊,心疼那个时候的程序员2秒

  • Spring2.0时代

    Spring引入了注解开发,但是因为并不完善,因此并未完全替代xml,此时的程序员往往是把xml与注解进行结合,貌似我们之前都是这种方式。

  • Spring3.0及以后

    3.0以后Spring的注解已经非常完善了,因此Spring推荐大家使用完全的java配置来代替以前的xml,不过似乎在国内并未推广盛行。然后当SpringBoot来临,人们才慢慢认识到java配置的优雅。

有句古话说的好:拥抱变化,拥抱未来。所以我们也应该顺应时代潮流,做时尚的弄潮儿,一起来学习下java配置的玩法。

3.2 尝试java配置

java配置主要靠java类和一些注解,比较常用的注解有:

  • @Configuration:声明一个类作为配置类,代替xml文件
  • @Bean:声明在方法上,将方法的返回值加入Bean容器,代替<bean>标签
  • @value:属性注入
  • @PropertySource:指定外部属性文件,

我们接下来用java配置来尝试实现连接池配置:

首先引入Druid连接池依赖(不要使用starter的方式引入,如果使用starter方式引入就自动配置了):

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.6</version>
</dependency>

创建一个jdbc.properties文件,编写jdbc属性:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/tony
jdbc.username=root
jdbc.password=123456

然后编写代码:

@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {

    @Value("${jdbc.url}")
    String url;
    @Value("${jdbc.driverClassName}")
    String driverClassName;
    @Value("${jdbc.username}")
    String username;
    @Value("${jdbc.password}")
    String password;

    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }
}

解读:

  • @Configuration:声明我们JdbcConfig是一个配置类
  • @PropertySource:指定属性文件的路径是:classpath:jdbc.properties
  • 通过@Value为属性注入值
  • 通过@Bean将 dataSource()方法声明为一个注册Bean的方法,Spring会自动调用该方法,将方法的返回值加入Spring容器中。

然后我们就可以在任意位置通过@Autowired注入DataSource了!

我们在HelloController中测试:

@RestController
public class HelloController {

    @Autowired
    private DataSource dataSource;

    @GetMapping("hello")
    public String hello() {
        return "hello, spring boot!" + dataSource;
    }
}

然后Debug运行并查看:

属性注入成功了!

3.3 SpringBoot的属性注入

在上面的案例中,我们实验了java配置方式。不过属性注入使用的是@Value注解。这种方式虽然可行,但是不够强大,因为它只能注入基本类型值。

在SpringBoot中,提供了一种新的属性注入方式,支持各种java基本数据类型及复杂类型的注入。

1)我们新建一个类,用来进行属性注入:

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {
    private String url;
    private String driverClassName;
    private String username;
    private String password;
    // ... 略
    // getters 和 setters
}

  • 在类上通过@ConfigurationProperties注解声明当前类为属性读取类
  • prefix="jdbc"读取属性文件中,前缀为jdbc的值。
  • 在类上定义各个属性,名称必须与属性文件中jdbc.后面部分一致
  • 需要注意的是,这里我们并没有指定属性文件的地址,所以我们需要把jdbc.properties名称改为application.properties,这是SpringBoot默认读取的属性文件名:

2)在JdbcConfig中使用这个属性:

@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {

    @Bean
    public DataSource dataSource(JdbcProperties jdbc) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(jdbc.getUrl());
        dataSource.setDriverClassName(jdbc.getDriverClassName());
        dataSource.setUsername(jdbc.getUsername());
        dataSource.setPassword(jdbc.getPassword());
        return dataSource;
    }
}
  • 通过@EnableConfigurationProperties(JdbcProperties.class)来声明要使用JdbcProperties这个类的对象

  • 然后你可以通过以下方式注入JdbcProperties:

    • @Autowired注入

      @Autowired
      private JdbcProperties prop;
      
    • 构造函数注入

      private JdbcProperties prop;
      public JdbcConfig(Jdbcproperties prop){
          this.prop = prop;
      }
      
    • 声明有@Bean的方法参数注入

      @Bean
      public Datasource dataSource(JdbcProperties prop){
          // ...
      }
      

本例中,我们采用第三种方式。

3)debug测试

3.4 更优雅的注入

事实上,如果一段属性只有一个Bean需要使用,我们无需将其注入到一个类(JdbcProperties)中。而是直接在需要的地方声明即可:

@Configuration
public class JdbcConfig {
    @Bean
    // 声明要注入的属性前缀,SpringBoot会自动把相关属性通过set方法注入到DataSource中
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        return dataSource;
    }
}

我们直接把@ConfigurationProperties(prefix = "jdbc")声明在需要使用的@Bean的方法上,然后SpringBoot就会自动调用这个Bean(此处是DataSource)的set方法,然后完成注入。使用的前提是:该类必须有对应属性的set方法!

4. 自动配置原理

使用SpringBoot之后,一个整合了SpringMVC的WEB工程开发,变的无比简单,那些繁杂的配置都消失不见了,这是如何做到的?

一切魔力的开始,都是从我们的main函数来的,所以我们再次来看下启动类:

我们发现特别的地方有两个:

  • 注解:@SpringBootApplication
  • run方法:SpringApplication.run()

我们分别来研究这两个部分。

4.1 @SpringBootApplication

这里重点的注解有3个:

  • @SpringBootConfiguration
  • @EnableAutoConfiguration
  • @ComponentScan

4.1.1 @SpringBootConfiguration

通过源码我们可以看出,在这个注解上面,又有一个@Configuration注解。通过上面的注释阅读我们知道:这个注解的作用就是声明当前类是一个配置类,然后Spring会自动扫描到添加了@Configuration的类,并且读取其中的配置信息。而@SpringBootConfiguration是来声明当前类是SpringBoot应用的配置类,项目中只能有一个。所以一般我们无需自己添加。

4.1.2 @EnableAutoConfiguration

关于这个注解,官网上有一段说明:

The second class-level annotation is @EnableAutoConfiguration. This annotation
tells Spring Boot to “guess” how you want to configure Spring, based on the jar
dependencies that you have added. Since spring-boot-starter-web added Tomcat
and Spring MVC, the auto-configuration assumes that you are developing a web
application and sets up Spring accordingly.

简单翻译以下:

第二级的注解@EnableAutoConfiguration,告诉SpringBoot基于你所添加的依赖,去“猜测”你想要如何配置Spring。比如我们引入了spring-boot-starter-web,而这个启动器中帮我们添加了tomcatSpringMVC的依赖。此时自动配置就知道你是要开发一个web应用,所以就帮你完成了web及SpringMVC的默认配置了!

总结,SpringBoot内部对大量的第三方库或Spring内部库进行了默认配置,这些配置是否生效,取决于我们是否引入了对应库所需的依赖,如果有那么默认配置就会生效。

所以,我们使用SpringBoot构建一个项目,只需要引入所需框架的依赖,配置就可以交给SpringBoot处理了。除非你不希望使用SpringBoot的默认配置,它也提供了自定义配置的入口。

4.1.3 @ComponentScan

查看注释,大概的意思:

配置组件扫描的指令。提供了类似与<context:component-scan>标签的作用

通过basePackageClasses或者basePackages属性来指定要扫描的包。如果没有指定这些属性,那么将从声明这个注解的类所在的包开始,扫描包及子包

而我们的@SpringBootApplication注解声明的类就是main函数所在的启动类,因此扫描的包是该类所在包及其子包。因此,一般启动类会放在一个比较前的包目录中。

4.2 默认配置原理

4.2.1 默认配置类

通过刚才的学习,我们知道@EnableAutoConfiguration会开启SpringBoot的自动配置,并且根据你引入的依赖来生效对应的默认配置。那么问题来了:

  • 这些默认配置是在哪里定义的呢?
  • 为何依赖引入就会触发配置呢?

其实在我们的项目中,已经引入了一个依赖:spring-boot-autoconfigure,其中定义了大量自动配置类,几乎涵盖了现在主流的开源框架,例如:

  • redis
  • jms
  • amqp
  • jdbc
  • jackson
  • mongodb
  • jpa
  • solr
  • elasticsearch

… 等等

我们来看一个我们熟悉的,例如SpringMVC,查看mvc 的自动配置类:

WebMvcProperties

打开:WebMvcAutoConfiguration

我们看到这个类上的4个注解:

  • @Configuration:声明这个类是一个配置类

  • @ConditionalOnWebApplication(type = Type.SERVLET)

    ConditionalOn,翻译就是在某个条件下,此处就是满足项目的类是是Type.SERVLET类型,也就是一个普通web工程,显然我们就是

  • @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })

    这里的条件是OnClass,也就是满足以下类存在:Servlet、DispatcherServlet、WebMvcConfigurer,其中Servlet只要引入了tomcat依赖自然会有,后两个需要引入SpringMVC才会有。这里就是判断你是否引入了相关依赖,引入依赖后该条件成立,当前类的配置才会生效!

  • @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

    这个条件与上面不同,OnMissingBean,是说环境中没有指定的Bean这个才生效。其实这就是自定义配置的入口,也就是说,如果我们自己配置了一个WebMVCConfigurationSupport的类,那么这个默认配置就会失效!

接着,我们查看该类中定义了什么:

视图解析器:

@Bean
@ConditionalOnMissingBean
public InternalResourceViewResolver defaultViewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix(this.mvcProperties.getView().getPrefix());
    resolver.setSuffix(this.mvcProperties.getView().getSuffix());
    return resolver;
}

处理器适配器(HandlerAdapter):

@Override
protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
    if (this.mvcRegistrations != null
        && this.mvcRegistrations.getRequestMappingHandlerAdapter() != null) {
        return this.mvcRegistrations.getRequestMappingHandlerAdapter();
    }
    return super.createRequestMappingHandlerAdapter();
}

还有很多…

4.2.2 默认配置属性

另外,这些默认配置的属性来自哪里呢?

@EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class })

我们看到,这里通过@EnableAutoConfiguration注解引入了两个属性:WebMvcProperties和ResourceProperties。这不正是SpringBoot的属性注入玩法嘛。

我们查看这两个属性类:

@ConfigurationProperties(prefix = "spring.mvc")
public class WebMvcProperties {

    /**
	 * Formatting strategy for message codes (PREFIX_ERROR_CODE, POSTFIX_ERROR_CODE).
	 */
    private DefaultMessageCodesResolver.Format messageCodesResolverFormat;

    /**
	 * Locale to use. By default, this locale is overridden by the "Accept-Language"
	 * header.
	 */
    private Locale locale;

    /**
	 * Define how the locale should be resolved.
	 */
    private LocaleResolver localeResolver = LocaleResolver.ACCEPT_HEADER;

    /**
	 * Date format to use (e.g. dd/MM/yyyy).
	 */
    private String dateFormat;

    /**
	 * Dispatch TRACE requests to the FrameworkServlet doService method.
	 */
    private boolean dispatchTraceRequest = false;
    .....
}

找到了内部资源视图解析器的prefix和suffix属性。

如果我们要覆盖这些默认属性,只需要在application.properties中定义与其前缀prefix和字段名一致的属性即可。

4.3.总结

SpringBoot为我们提供了默认配置,而默认配置生效的条件一般有两个:

  • 你引入了相关依赖
  • 你自己没有配置

1)启动器

所以,我们如果不想配置,只需要引入依赖即可,而依赖版本我们也不用操心,因为只要引入了SpringBoot提供的stater(启动器),就会自动管理依赖及版本了。

因此,玩SpringBoot的第一件事情,就是找启动器,SpringBoot提供了大量的默认启动器(常用依赖)

2)全局配置

另外,SpringBoot的默认配置,都会读取默认属性,而这些属性可以通过自定义application.properties文件来进行覆盖。这样虽然使用的还是默认配置,但是配置中的值改成了我们自定义的。

因此,玩SpringBoot的第二件事情,就是通过application.properties来覆盖默认属性值,形成自定义配置。我们需要知道SpringBoot的默认属性key,非常多.

5. SpringBoot实践

5.1 整合SpringMVC

虽然默认配置已经可以使用SpringMVC了,不过我们有时候需要进行自定义配置。

5.1.1 修改端口

查看SpringBoot的全局属性可知,端口通过以下方式配置:

# 映射端口
server.port=80

重启服务后测试:

5.1.2 访问静态资源

现在,我们的项目是一个jar工程,那么就没有webapp,我们的静态资源该放哪里呢?

回顾我们上面看的源码,有一个叫做ResourceProperties的类,里面就定义了静态资源的默认查找路径:

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
                                                                  "classpath:/resources/", "classpath:/static/", "classpath:/public/" };
    .....
}

默认的静态资源路径为:

  • classpath:/META-INF/resources/
  • classpath:/resources/
  • classpath:/static/
  • classpath:/public

只要静态资源放在这些目录中任何一个,SpringMVC都会帮我们处理。

我们习惯会把静态资源放在classpath:/static/目录下。我们创建目录,并且添加一些静态资源:

dijia.jpg

重启项目后测试:

  • http://localhost:8888/dijia.jpg

5.1.3 添加拦截器

拦截器也是我们经常需要使用的,在SpringBoot中该如何配置呢?

拦截器不是一个普通属性,而是一个类,所以就要用到java配置方式了。在SpringBoot官方文档中有这么一段说明:

If you want to keep Spring Boot MVC features and you want to add additional MVC configuration (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc. If you wish to provide custom instances of·RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

翻译:

如果你想要保持Spring Boot 的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器, 视图控制器、消息转换器 等等),你应该让一个类实现WebMvcConfigurer,并且添加@Configuration注解,但是**千万不要**加@EnableWebMvc注解。如果你想要自定义HandlerMappingHandlerAdapterExceptionResolver等组件,你可以创建一个WebMvcRegistrationsAdapter`实例 来提供以上组件。

如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一切特征,你可以自己定义类并且添加@Configuration注解和@EnableWebMvc注解

总结:通过实现WebMvcConfigurer并添加@Configuration注解来实现自定义部分SpringMvc配置。

首先我们定义一个拦截器:

package com.xzy.springboot.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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


@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截到处理器的请求了");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

然后,我们定义配置类,注册拦截器:

package com.xzy.springboot.config;

import com.xzy.springboot.interceptor.MyInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyInterceptorConf implements WebMvcConfigurer {
    @Autowired
    private MyInterceptor myInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**");
    }
}

接下来运行并查看日志:

你会发现日志中什么都没有,因为我们记录的log级别是debug,默认是显示info以上,我们需要进行配置。

SpringBoot通过logging.level.*=debug来配置日志级别,*填写包名

# 设置com.up包的日志级别为debug
logging.level.com.uplooking=debug

再次运行查看:

2018-05-05 17:50:01.811 DEBUG 4548 --- [p-nio-80-exec-1] com.up.interceptor.LoginInterceptor   : preHandle method is now running!
2018-05-05 17:50:01.854 DEBUG 4548 --- [p-nio-80-exec-1] com.up.interceptor.LoginInterceptor   : postHandle method is now running!
2018-05-05 17:50:01.854 DEBUG 4548 --- [p-nio-80-exec-1] com.up.interceptor.LoginInterceptor   : afterCompletion method is now running!

5.2 整合连接池

其实,在刚才引入jdbc启动器的时候,SpringBoot已经自动帮我们引入了一个连接池HikariCP(jdbc-start中东西)

应该是目前速度最快的连接池了,我们看看它与c3p0的对比:

c3p0: 234
hikari:50273

因此,我们只需要指定连接池参数即可:

  • application.properties
server.port=8888

# 配置连接池
# 连接四大参数
# 可省略,SpringBoot自动推断
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/tony?serverTimeZone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456

当然,如果你更喜欢Druid连接池,也可以使用Druid官方提供的启动器:

<!-- Druid连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.6</version>
</dependency>

而连接信息的配置与上面是类似的,只不过在连接池特有属性上,方式略有不同:

#初始化连接数
spring.datasource.druid.initial-size=1
#最小空闲连接
spring.datasource.druid.min-idle=1
#最大活动连接
spring.datasource.druid.max-active=20
#获取连接时测试是否可用
spring.datasource.druid.test-on-borrow=true
#监控页面启动
spring.datasource.druid.stat-view-servlet.allow=true

5.3 整合mybatis

#控制台打印mybatis生成的sql
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

5.3.1 mybatis依赖

SpringBoot官方并没有提供Mybatis的启动器,不过Mybatis官网自己实现了:

<!--mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
  • application.properties
# mybatis 别名扫描
# mybatis.type-aliases-package=com.up.pojo
# mapper.xml文件位置,如果没有映射文件,请注释掉
mybatis.mapper-locations=classpath:mappers/*.xml

需要注意,这里没有配置mapper接口扫描包,因此我们需要给每一个Mapper接口添加@Mapper注解,才能被识别。

package com.xzy.springboot.dao;

import com.xzy.springboot.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;

@Mapper
public interface UserMapper {
    User selectById(@Param("id") Integer id);
}

  • /src/main/resources/mappers/UserMapper.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xzy.springboot.dao.UserMapper">
    <select id="selectById" resultType="com.xzy.springboot.entity.User">
        select *
        from user
        where id = #{id}
    </select>
</mapper>
  • UserService
package com.xzy.springboot.service;

import com.xzy.springboot.dao.UserMapper;
import com.xzy.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User findById(Integer id) {
        User user = userMapper.selectById(id);
        return user;
    }
}
  • UserController
package com.xzy.springboot.controller;

import com.xzy.springboot.entity.User;
import com.xzy.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping("/find")
    public User find(Integer id) {
        User user = userService.findById(id);
        return user;
    }
}

http://localhost:8888/user/find?id=2

在这里插入图片描述

5.4 整合jdbc和事务

spring中的jdbc连接和事务是配置中的重要一环,在SpringBoot中该如何处理呢?

答案是不需要处理,我们只要找到SpringBoot提供的启动器即可:

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

当然,不要忘了数据库驱动,SpringBoot并不知道我们用的什么数据库,这里我们选择MySQL:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

至于事务,SpringBoot中通过注解来控制。就是我们熟知的@Transactional

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User queryById(Long id){
        return this.userMapper.selectByPrimaryKey(id);
    }

    @Transactional
    public void deleteById(Long id){
        this.userMapper.deleteByPrimaryKey(id);
    }
}

6. Thymeleaf快速入门

SpringBoot并不推荐使用jsp,但是支持一些模板引擎技术:

以前大家用的比较多的是Freemarker,但是我们今天的主角是Thymeleaf!

6.1 为什么是Thymeleaf?

简单说, Thymeleaf 是一个跟 Velocity、FreeMarker 类似的模板引擎,它可以完全替代 JSP 。相较与其他的模板引擎,它有如下三个极吸引人的特点:

  • 动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以 thymeleaf 的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
  • 开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
  • 多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
  • 与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。代码几乎没有任何区别,就是在模板语法上有区别。

接下来,我们就通过入门案例来体会Thymeleaf的魅力:

6.2 编写接口

编写一个controller,返回一些用户数据,放入模型中,等会在页面渲染

@GetMapping("/all")
public String all(ModelMap model) {
    // 查询用户
    List<User> users = this.userService.queryAll();
    // 放入模型
    model.addAttribute("users", users);
    // 返回模板名称(就是classpath:/templates/目录下的html文件名)
    return "users";
}

6.3 引入启动器

直接引入启动器:

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

SpringBoot会自动为Thymeleaf注册一个视图解析器

  • 默认前缀:classpath:/templates/
  • 默认后缀:.html

所以如果我们返回视图:users,会指向到 classpath:/templates/users.html

一般我们无需进行修改,默认即可。

6.4 th:text

<h1 th:text="${name}">h1h1h1h1h1</h1>
${名称}就可以获取model中的数据,原来的数据"h1h1h1h1h1"不需要删除,当${名称}获取到model中的值时,就会自动替换数据,这样方便做到 前后端互相分离

6.5 引入url

<a th:href="${murl}" href="http://www.baidu.com">this is me </a>
<img th:src="${msrc}"  src="/1.png" />

6.6 字符串的拼接

<h2 th:text="ff+${msrc}+${mname}">h2h2h2h2</h2>

6.7 运算符

在表达式中可以使用各类算术运算符,例如+, -, *, /, %

<p th:text="${age}+12">this is p</p>

逻辑运算符>, <, <=,>=,==,!=都可以使用,唯一需要注意的是使用<,>时需要用它的HTML转义符: > <

6.8 条件表达式if/unless

Thymeleaf中使用th:if和th:unless属性进行条件判断,下面的例子中,标签只有在th:if中条件成立时才显示:

<h3 th:text="${mage}" th:if="${mage} > 120">myh3h3h3</h3>

th:unless于th:if恰好相反,只有表达式中的条件不成立,才会显示其内容

<h3 th:text="${mage}" th:unless="${mage} > 120">myh3h3h3</h3>

6.9 switch分支

<div th:switch="${age}">
        <p th:case="12" th:text="${age}"></p>
        <p th:case="13" th:text="${age}"></p>
   </div>

6.10 each 循环

渲染列表数据是一种非常常见的场景,例如现在有n条记录需要渲染成一个表格

<ul th:each="name:${names}">
        <li th:text="${name}"></li>
</ul>

6.11 模板缓存

Thymeleaf会在第一次对模板解析之后进行缓存,极大的提高了并发处理能力。但是这给我们开发带来了不便,修改页面后并不会立刻看到效果,我们开发阶段可以关掉缓存使用:

# 开发阶段关闭thymeleaf的模板缓存
spring.thymeleaf.cache=false

注意

在Idea中,我们需要在修改页面后按快捷键:`Ctrl + Shift + F9` 对项目进行rebuild才可以。

6.12 thymeleaf老版本标签闭合问题

在Thymeleaf 2.x版本中,要求HTML中元素标签必须要闭合,但是在3.x版本中已经不存在该问题了,但是在Springboot 1.5.9版本中,使用的Thymeleaf版本依然是2.x版本,因此要么在构建脚本中覆盖Springboot默认的Thymeleaf版本,或者使用更高版本的Springboot。

经测试,使用2.0.0 M7版本Springboot,默认使用了3.x版本的Thymeleaf,可以解决HTML元素标签不闭合的问题。

在thymeleaf2.x中的解决方案:

<!--SpringBoot的ThyMeLeaf关闭严格检查模式-->
<dependency>
    <groupId>net.sourceforge.nekohtml</groupId>
    <artifactId>nekohtml</artifactId>
    <version>1.9.22</version>
</dependency>

application.yaml
#禁用thymeleaf的严格检查模式
spring:
  thymeleaf:
    cache: false
    mode: LEGACYHTML5

7. SpringBoot热部署

7.1 添加pom依赖

<!--SpringBoot热部署的插件-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>

7.2 修改配置文件application.properties

spring.thymeleaf.cache=false

7.3 修改idea自动编译java

file--->other settings--->default settings---->Build--->compiler--->build project autoxxxx(勾选)

ps:这个自动编译的设置只是针对在没有运行程序的情况下自动编译

7.4 修改idea运行中的自动编译

help--->find action--->Registry--->compiler.automake.allow.when.app.running(勾选)

高版本的idea自身也可以不借助插件实现SpringBoot热部署,run–config–update classes and resources…

8. SpringBoot全局异常处理

  • 创建异常处理器(声明为控制器通知)
package com.xzy.springboot.entity;

import lombok.Data;

@Data
public class Response {
    private Integer code;
    private String msg;
}

package com.xzy.springboot.exception;

import com.xzy.springboot.entity.Response;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Response handlerException(Exception e){
        Response response = new Response();
        response.setCode(8888);
        response.setMsg("Exception类型的异常");
        return response;
    }
}

在代码中制造异常就可以由异常处理器统一处理

9. SpringBoot 中的单元测试

9.1 pom依赖

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

9.2 编写测试用例

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Spring入口.class)
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void testFindUserById() {
        User user = userService.findUserByID(2);
        System.out.println(user);
    }
}

10. 返回值为json

在SpringBoot中默认支持返回json,SpringBoot提供了很优雅的方式

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String name;
    private Integer age;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date birthday;
}

使用@RestController

import com.uplooking.springbootstudy.pojo.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
@RestController
@RequestMapping("user")
public class UserController {
    @RequestMapping("userinfo/{id}")
    private User userInfo(@PathVariable("id") Integer id) {
        User user = new User(1, "tom", 20, new Date());
        return user;
    }
}

11. 使用SpringBoot发送邮件

  • pom依赖

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.1.7.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>
    </dependencies>
    
  • 配置application.properties

    #设置代发邮箱服务器的主机
    spring.mail.host=smtp.qq.com
    #配置邮箱的用户名(邮箱地址xxx@qq.com)
    spring.mail.username=2956923596@qq.com
    #配置密码(是授权码)
    spring.mail.password=xxxxx
    #配置发送和接收的邮箱
    mail.from=2956923596@qq.com
    mail.to=2683608759@qq.com
    
  • 创建Java配置类,读取自定义配置

    package com.uplooking.mail;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    @ConfigurationProperties(prefix = "mail")
    public class MailConfProperties {
        private String from;
        private String to;
    
        public MailConfProperties() {
        }
    
        public MailConfProperties(String from, String to) {
            this.from = from;
            this.to = to;
        }
    
        public String getFrom() {
            return from;
        }
    
        public void setFrom(String from) {
            this.from = from;
        }
    
        public String getTo() {
            return to;
        }
    
        public void setTo(String to) {
            this.to = to;
        }
    
        @Override
        public String toString() {
            return "MailConfProperties{" +
                    "from='" + from + '\'' +
                    ", to='" + to + '\'' +
                    '}';
        }
    }
    
    
  • 发送邮件

    package com.uplooking.mail;
    
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSenderImpl;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    @SpringBootApplication
    @EnableConfigurationProperties(MailConfProperties.class)
    public class Application implements CommandLineRunner {
        @Autowired
        private MailConfProperties mailConfProperties;
        @Autowired
        private JavaMailSenderImpl javaMailSender;
    
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    
        @Override
        public void run(String... args) throws Exception {
            sendMail() ;
    
        }
    
        /**
         * 邮件发送
         */
        public void sendMail() {
            SimpleMailMessage smm = new SimpleMailMessage();
            smm.setFrom(mailConfProperties.getFrom());
            smm.setTo(mailConfProperties.getTo());
            smm.setSubject("this is subject");
            smm.setText("this is content...");
            javaMailSender.send(smm);
    
        }
    }
    

12. SpringBoot打包

<plugins>
    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
    </plugin>
</plugins>

13 lombok自带的日志工具

@slf4j
log.info();
log.error();
log.warn();
log.debug();

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值