Spring Boot入门

1.SpringBoot简介

简化SPring开发的一个框架;

整合Spring技术栈的一个大集合

J2EE开发的一站式解决方案

微服务

微服务是一种架构风格

一个应用应该是一组小型服务:可以通过HTTP的方式进行互通

每一个功能元素最终都是一个可独立替换和升级的软件单元

微服务文档

Spring Boot HelloWorld

1.创建Maven 工程

2.导入相关依赖

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

3.主程序启动SpringBoot

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

4编写相关的Controller、、、

@Controller
public class HelloController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello(){
        return "Hello World";
    }
}

5.运行主程序测试

6.简化部署

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

将这个应用打包成Jar包,直接使用-java -jar运行

SpringBoot配置文件

​ SpringBoot使用一个全局配置文件

​ application.properties

​ application.yml

作用:修改Spring Boot的默认值;

YAML:一个标记语言

标记语言:以前大多数配置文件都是 xxx.xml文件

以数据为中心,比Json\xml等更适合做配置文件

1.三种配置方式

xml配置方式:

<server>
	<port>8081</port>
</server>

application.properties配置方式

server.port=8081

application.yml配置方式

server:
  port: 8081

2.YAML语法

1.基本语法:

K: v:表示一对键值对(必须有空格)

空格的缩进来控制层级的关系;只要左对齐的一列数据,都是同一个层级的

server:
  port:8080
  path:/hello

属性和值大小写敏感

2.值的写法字面量

(数字,字符串,布尔)

​ K:v:字面直接来写

​ 字符串默认不加单引号或双引号

​ "":双引号会转义字符串里面的特殊字符

​ name:"zhangsan \n lisi" 输出:zhangsan 换行 lisi

​ '':单引号不会转义特殊字符

​ name:"zhangsan \n lisi" 输出:zhangsan \n lisi

对象,Map(属性和值)(键值对)

​ 对象还是k:v的值

friends:
	lastname:zhangsan
	age:20

行内写法

friends:{lastName:zhangsan,age:20}

数组(List Set)

用值表示数组中的一个元素

pets:
- cat
- dog
- pig

行内写法

pets:[cat,dog,pig]

3.配置文件注入

配置文件:

server:
  port: 8081

person:
   lastName: zhangsan
   age: 18
   boss: false
   birth: 2017/12/12
   maps: {k1: v1,k2: v2}
   lists:
     - lisi
     - zhaoliu
   dog:
     name: 小狗
     age: 2

JavaBean:

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    
     /**
      * @description: 把每一个属性的值映射到组件中
      */
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;

    private Map<String ,Object > maps;
    private List<Object>lists;
    private Dog dog;

我们可以导入配置文件处理器。以后编写配置文件就有提示了

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

两种注解的比较

image-20200816000153150

@PropertySource&@ImportResource

@PropertySource:加载指定的配置文件

image-20200816225818485

@ImportResource:导入Spring的配置文件,让配置文件内的内容生效

SpringBoot里面没有Spring的配置文件。我们自己写的配置文件,也不能自动识别

想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类

image-20200816230827053

image-20200816230924331

SptringBoot推荐给容器中添加组建的方式:推荐使用全注解方式

1.配置类====Spring配置文件

2.使用@Bean给容器添加组件

image-20200816231834694

配置文件占位符

1、随机数

image-20200817113435140

2.占位符获取之前配置的值,如果没有可以设置默认值

image-20200817113548183

Profile

1.多Profile文件

我们在配置文件编写的时候,文件名可以是application-.properties/yml

默认使用application.properties

image-20200817114905310

2.yml支持多文档块方式

image-20200817115454532

3.激活指定Profile

image-20200817114925425

1.在配置文件中指定 spring.profiles.cative=dev

2.命令行:

--spring.profiles.active=dev

打包后的命令行

java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profiles.active=prod

可以直接在测试时,传入命令行参数

image-20200817115817429

image-20200817120220370

3.虚拟机参数

-Dspring.profiles.active=dev

image-20200817120505331

配置文件加载位置(优先级)

image-20200817171214218

image-20200818175136302

优先级由高到低,高优先级配置会覆盖低优先级的配置;

SpringBoot会从这四个位置全部加载主配置文件:互补配置

image-20200817171943050

image-20200817172015097

==我们还可以通过spring.config.location来改变默认的配置文件位置==

项目打包后,可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件共同起作用形成互补配置

image-20200817172748534

自动配置原理

自动配置原理

1)SpringBoot启动的时候加载主配置类,开启了自动配置功能**@EnableAutoConfiguration**

2)@EnableAutoConfiguration作用:

​ 利用EnableAutoConfigurationImportSelector给容器中导入一些组件?

​ 可以插件selectImports()的内容 获取候选的配置

 List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());

将类路径下META/INF/spring.factories里面所用EnableAutoConfigration的值加入到容器中

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration

3)每一个这样的类:xxxAutoConfigration类都是容器中的一个组件;都加入到容器中;用他们来做自动配置

4)以HttpEncodingAutoConfiguration为例解释自动配置原理

@Configuration(
    proxyBeanMethods = false
)   //表示这是一个配置类,和配置文件一样,向容器中添加组件
@EnableConfigurationProperties({ServerProperties.class}) //启动指定的ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;并把HttpEncodingProperties加入到IOC容器中
@ConditionalOnWebApplication(  //Spring底层@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效;  判断当前应用是否是web应用,如果是当前配置类生效。
    type = Type.SERVLET
)
@ConditionalOnClass({CharacterEncodingFilter.class}) //判断当前项目是否存在这个类CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器

@ConditionalOnProperty( //判断配置文件中是否存在某个配置server.servlet.encoding.enable;如果不存在也为true;
    //即使不配置为true也默认为生效
    prefix = "server.servlet.encoding",
    value = {"enabled"},
    matchIfMissing = true
)


public class HttpEncodingAutoConfiguration {
    
    //他已经和springBoot的配置文件映射
    private final Encoding properties;
    //只有一个油藏构造器的情况下,参数的值从容器中拿
    public HttpEncodingAutoConfiguration(ServerProperties properties) {
        this.properties = properties.getServlet().getEncoding();
    }
    
    
    @Bean //给容器中添加一个组件;这个组件的某些值需要从properties中获取
    @ConditionalOnMissingBean
    public CharacterEncodingFilter characterEncodingFilter() {
        CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
        filter.setEncoding(this.properties.getCharset().name());
        filter.setForceRequestEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
        filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
        return filter;
    }
}

根据当前不同的条件判断,决定这个配置类是否生效

一旦这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;

5)所有配置文件中能配置的属性都是在xxxProperties类中的封装者;配置文件将能配置什么就可以参照某个功能对应的这个属性类

@ConfigurationProperties(   //从配置文件中获取指定的值和Bean的属性进行绑定
    prefix = "server",
    ignoreUnknownFields = true
)

精髓:

1)SpringBoot启动会加载大量的自动配置类

2)我们看我们需要的功能有没有SpringBoot默认写好的自动配置类

3)我们在看这个自动配置类中到底配置了那些组件(只要我们要用到的组件有,我们就不需要再来配置类)

4)给容器中自动配置类添加组件的时候,会从Properties类中获取某些属性。我们就可以在配置文件中指定这些属性

xxxAutoConfigurartion:自动配置类

给容器中添加组件

xxxProperties:封装配置文件中相关属性;

细节

@Conditional:条件为true则像容器中添加组件,配置里面的所有内容才生效

image-20200818190716900

自动配置类必须在一定条件下才能生效

我们怎么知道那些自动配置类生效

启动Debug=ture属性让控制台打印报告,我们就可以很方便的知道那些配置类生效

image-20200818191548079

Spring Boot与日志

日志

1.日志框架

底层是SpringBoot;底层是Spring框架,Spring框架默认用的是JCL

SpringBoot选用SLF4和logback

2.SLFj的使用

1.如何在系统中使用SLF4j

开发的时候,日志记录方法的调用,不应该来直接俄调用日志的实现类,而是调用日志抽象层的方法:

给系统里面导入slf4j的Jar和logback的实现Jar

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HelloWorld {
  public static void main(String[] args) {
    Logger logger = LoggerFactory.getLogger(HelloWorld.class);
    logger.info("Hello World");
  }

image-20200819230535396

每一个日志的实现框架都有自己的配置文件,使用slf4j以后**,配置文件还是做成日志实现框架自己本身的配置文件**

2.依赖框架

a(slf4j+logback):Spring(commons-logging)Hibernate(jboss-logging)

统一日志记录,即使是别的框架和我一起统一使用slf4j进行输出

image-20200819231517927

==如何让系统中所有的日志统一到dslf4j?==

  1. ==将系统中其他日志框架先排除出去:==
  2. ==用中间包来替换原有的日志框架;==
  3. ==导入slf4j其他的实现==

3.Spring Boot日志关系

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

​ SpringBoot使用它来

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-logging</artifactId>
      <version>2.3.3.RELEASE</version>
      <scope>compile</scope>
    </dependency>

image-20200819232853247

总结:

1)SB底层也是使用slf4j+logback的记录方式进行日志记录

  1. SB也把其他的日志都替换成了slf4j

  2. 中间替换包

4)如果要引入其他框架,一定要把这个框架的默认依赖移除掉

​ SP使用的是commons-logging

SP能自动适配所有的日志,而且底层使用slf4j_logback的方式记录日志,引入其他框架的时候自动排出

4.日志使用;

1.默认配置

​ SP默认配置好了日志;

image-20200819235036010

image-20200819235053431

Logging.file.name

image-20200819235804460

Logging.file.path

image-20200819235712590

Logging.pattern.file & Logging.pattern.console

image-20200820000418187

四、Web开发

使用SB开发

1)创建项目应用选中所需要的组件

2)SB默认配置好场景,只需要在配置文件中指定少量配置就可以运行起来

3)自己编写业务代码

自动配置原理:

五、整合数据库

1.整合Druid

image-20201004002500755

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/plant
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    initiaSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    filters: stat,wall,log4j
    MaxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    ConnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

config/DruidConfig


@Configuration
public class DruidConfig {

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

    //配置监控
    //1. 管理后台的Servlet

    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        Map<String, String> initMaps = new HashMap<>();

        initMaps.put("loginUsername", "admin");
        initMaps.put("loginPassword", "admin");
        // 不写允许所有
        initMaps.put("allow", "");

        bean.setInitParameters(initMaps);
        return bean;
    }

    //2. 配置Filtter
    public FilterRegistrationBean WebStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());

        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);

        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

2.整合Mybatis

配置Druid

配置MyBatis驼峰命名

路径在/config/MyBatisConfig

@org.springframework.context.annotation.Configuration
public class MyBatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return new ConfigurationCustomizer() {
            @Override
            public void customize(Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

使用MapperScan批量扫描Mapper所有的接口
@MapperScan(value = "com.atfuigu.springboot06mybatis.mapper")

xml文件使用驼峰命名

resources/mybatis/mybatis-config.xml

<configuration>
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>

Q.E.D.


纵我不往,子宁不嗣音?。纵我不往,子宁不来?