springBoot初級入門

springBoot初級入門

獲取配置文件中的值@ConfigurationProperties

1、這個注解默認只能從全局配置文件中獲取信息,全局配置有兩個,如下:

1、application.properties

2、application.yml

yml

1、key和value之間需要空格

2、縮進顯示層次關系,縮進多少無所謂,只要左對齊那么就是一個層級關系的

3、key: value :: 表示一個鍵值對,注意一定要有空格

4、大小寫敏感

5、屬性的值如果是字符串可以直接寫,不需要加上雙引號或者單引號

1、雙引號:加上雙引號的值不會轉義里面的特殊字符,比如字符串中包含一個換行符,那么就會在輸出的時候換行

2、單引號:會轉義特殊的字符,會直接輸出換行符為`\n`

6、List和Set的表示方法:

# key與value之間空格
pets:
    - dog
    - pig
    - cat

## 行內的寫法:
pets: [dog,pig,cat]

7、Map<key,value>的寫法

map: {name: Jack,age: 22,gender: 女}

8、舉例

1、JavaBean:

/**
 * ConfigurationProperties : 這個注解表示這個實體類的值來自于配置文件中,當然包括properties和yaml文件
 *                          prefix表示這個配置文件中的前綴
 */
@Component  //注入到容器中
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private int age;
    private List<Object> list;
    private Map<String,Object> map;
    private User user;
    private Date birthday;
}

2、application.yml

person:
  name: 陳加兵
  age: 22
  list:
    - zhangsan
    - lisi
  user:
    name: 鄭元梅
    age: 22
  map: {name: Jack,age: 22,gender: 女}
  birthday: 2012/12/11

3、添加一個依賴,將會在配置文件中自動提示

    <!--導入這個處理器,在配置文件中將會自動提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

4、測試類:

@RunWith(SpringRunner.class)
@SpringBootTest
public class TeammissionServerApplicationTests {
    @Autowired
    private Person person;   //自動注入

    @Test
    public void contextLoads() {
        System.out.println(person);   //輸出配置信息
    }

}

properties

1、依然可以使用@ConfigurationProperties這個注解獲取配置文件的值,不過和yml文件中的配置有很大的區別,如下:

person.age=22
person.name=陳加兵
person.birthday=2012/12/11
person.list=a,b,c
person.map.name=陳加兵
person.map.age=22
person.user.name=Jack
person.user.age=33

@Value

1、這個注解是spring中的注解,用于獲取配置文件的值

使用方式 作用
@Value("${}") 獲取配置文件中的值
@Value("#{}") 獲取配置文件中的值,不過需要使用<util:>這個指定id
@Value("value") 可以直接為變量賦值

2、不支持JSR303校驗

@PropertySource

1、我們在使用@configurationProperties獲取文件中的信息的時候,默認只能從默認的配置文件中獲取信息,如果我們需要自己單獨定義一個配置文件,那么需要使用@PropertySource這個注解獲取其中的信息

2、 我們在項目路徑下新建一個person.properties文件,其中的內容如下:

person.age=22
person.name=陳加兵
person.birthday=2012/12/11
person.list=a,b,c
person.map.name=陳加兵
person.map.age=22
person.user.name=Jack
person.user.age=33

3、在Person這個實體類中添加如下的注解配置,使用@PropertySource這個注解加載這個配置文件,如下:

/**
 * ConfigurationProperties : 這個注解表示這個實體類的值來自于配置文件中,當然包括properties和yaml文件
 *                          prefix表示這個配置文件中的前綴
 */
@PropertySource(value ={"classpath:person.properties"})   //從自定義的配置文件中獲取信息
@Component  //注入到容器中
@ConfigurationProperties(prefix = "person")   //獲取前綴為person的信息
public class Person {

    private String name;
    private int age;
    private List<Object> list;
    private Map<String,Object> map;
    private User user;
    private Date birthday;
}

4、使用@PropertySource這個注解能夠導入自定義的配置文件并且獲取其中的值

5、 使用這個注解只能加載properties文件,無法加載YAML文件

@ImportSource

1、在springBoot中幾乎沒有配置文件,全部都是使用注解,那么我們如果需要使用配置文件,我們該如何讓這個配置文件生效呢?

2、我們可以使用這個注解加載自己的配置文件xml,不過在springBoot中不贊成這樣做,因為可以使用配置類來代替配置文件xml

3、我們在項目的resource文件下新建一個beans.xml,其中配置了如下的信息:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="person" class="com.telles.teammissionserver.bean.Person">
        <property name="age" value="22"></property>
        <property name="name" value="陳加兵"></property>
    </bean>

</beans>

4、我們現在需要將其加入到IOC容器中,必須使用@ImportSource這個注解,我們需要在項目的主配置類上添加這個注解導入配置文件

//使用這個注解可以導入自定義的配置文件xml,其中的value值是一個數組,可以填寫多個值
@ImportResource(value = {"classpath:beans.xml"})
@SpringBootApplication
public class TeammissionServerApplication {

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

配置類

1、我們在springBoot中已經完全舍棄了配置文件的形式來為容器注入組件,我們都是使用配置類的形式,每個項目在建立的時候都有一個主配置類,使用SpringBootApplication這個注解來標注的,我們也可以定義自己的配置類,只要使用@Configuration這個注解標注即表示當前類是一個配置類。

2、我們在新建一個包config專門存放配置類,在其中可以建立多個配置類,如下:

@Configuration  //指定這是一個配置類
public class MainConfig {
    /**
     * @Bean: 這個注解將其注入到IOC容器中
     * 其中的返回類型Person就相當于class,方法名就是返回的id,在IOC容器中我們可以使用這個id獲取自動
     * 配置的實例
     */
    @Bean
    Person person(){
        Person person=new Person();
        person.setAge(22);
        person.setName("chen");
        return person;
    }
}

配置文件占位符

1、可以使用隨機數,如下:

## 使用隨機的uuid為其復制
person.name=${random.uuid}
## 配置一個隨機的int
person.age=${random.int}

2、可以使用占位符獲取之前配置的值,如果沒有可以使用:指定默認值

## 配置一個隨機的int
person.age=${random.int}
# 使用占位符獲取之前配置的值,如果這個值不存在,那么使用指定的默認值
person.user.age=${person.age:33}

多環境開發

1、我們在開發的時候可能會面對多環境,比如生產環境,測試環境,上線運行環境,針對這幾種不同的環境,我們可能需要的配置也是不相同的,此時我們就需要在不同的環境之間切換不同的配置文件。

properties

1、我們可以在創建不同的properties文件,文件名如:application-{profile}.properties,比如,application-dev.propertiesapplication-prod.properties這兩個文件,此時我們可以springBoot的朱主配置文件中application.properties文件中添加如下的語句,用來激活某一種的配置文件:

# 激活dev配置文件,那么此時springBoot就會以application-dev.properties文件為配置文件
spring.profiles.active=dev

yaml

1、在yaml中不需要建立多個文件,因為yaml可以使用---區分不同的文檔,只要在一個主配置文件application.yml中添加不同區域的文檔,即使表示不同的文件,如下:

## 文檔塊1,此時激活dev
server:
  port: 8081
spring:
  profiles:
    active: dev

---


## dev環境的配置
server:
  port: 8080
spring:
  profiles: dev

---

## prod環境的配置
server:
  port: 8088
spring:
  profiles: prod

配置文件加載位置

1、springBoot項目創建的時候在classpath路徑下的有一個application.properties文件,這個就是springBoot默認的文件位置,但是我們還可以在其他的位置指定配置文件,依然會生效。

2、springBoot有以下的位置可以放置配置文件,按照優先級由高到低如下:

1、項目路徑下的config文件夾中

2、直接放在項目路徑下

3、classpath路徑下的config文件夾中

4、直接放在classpath路徑下【創建項目的時候默認位置】

3、classpth即是resource文件夾下

4、注意:無論放在哪個位置,默認加載的文件名稱必須是application.properties

5、如果高優先級和低優先級共有的配置,那么高優先級會覆蓋低優先級的配置,但是高優先級配置文件中的沒有的配置,如果在低優先級的配置文件中存在,那么依然會生效,這樣就可以形成互補的形式

6、可以在默認的配置文件application.properties文件中使用spring.config.location來指定外部的配置文件,如下:

spring.config.location=/usr/local/application.properties

7、在項目已經發布出去之后,我們也可以使用命令行的方式指定配置文件的位置,如:java -jar springboot.jar --spring.config.location=/usr/local/application.properties

日志框架

1、spring默認的規定的日志框架是self4j和logback,這是目前的主流的日志框架,如果想要使用self4j和log4j,那么需要使用指定的適配類進行接口的轉換。轉換關系如下圖:

[圖片上傳失敗...(image-25c743-1538922709906)]

2、默認什么都不配置的情況下,日志是開啟的,使用的是self4j+logback,日志的級別是info

3、我們可以在全局配置文件appliction.properties或者application.yml中修改默認的配置,比如修改默認的日志級別,控制臺輸出格式,輸出的日志文件的位置

4、日志的輸出級別由高到低的級別如下:ERROR, WARN, INFO, DEBUG, or TRACE.

5、在springBoot中支持自定義的日志配置如下:

# 指定com.telles包下的所有類下的日志輸出級別為debug,可以指定某個類或者某個包下的類所使用的日志級別
logging.level.com.telles=error


# 如果指定的相對路徑,那么就是在當前項目下,如果指定的了絕對路徑,比如c:\\log\\spring.log,那么就是在指定的位置上生成log輸出的文件
logging.file=log/spring.log

# 也是指定的日志的文件的位置,不過是在當前項目的所在根目錄下指定的文件的位置,比如/log/spring.log,這個就是在該項目的根目錄中的log文件夾下指定的日志文件是spring.log
logging.path=/log/spring.log

# 指定控制臺輸出的格式,但是也是有默認的格式,這個和log4j的配置是一樣的
logging.pattern.console=

# 指定日志文件的輸出格式
logging.pattern.file=

# 指定文件最大大小
logging.file.max-size=

# 指定日期的格式
logging.pattern.dateformat=

## 文件最大保存歷史量
logging.file.max-history=

6、當然也可以使用自定義的配置文件,但是命名有一定的規范,否則springBoot并不能自動識別,比如如果使用logback日志框架的話,那么自定義的配置文件的名稱必須是logback-xxx.xml,放在resource文件夾下,否則將不能識別,基本的配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定義日志文件的存儲地址 一般存儲在服務器的文件夾中-->
    <property name="LOG_HOME" value="/tmp/logs" />

    <!-- 控制臺輸出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化輸出-->
            <pattern>[%p]-[%c] - %m%n</pattern>
        </encoder>
    </appender>

    <!-- 按照每天生成日志文件 -->
    <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件輸出的文件名,使用日期進行拼接-->
            <FileNamePattern>${LOG_HOME}/web.log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天數-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日志消息,%n是換行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>100MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <!-- show parameters for hibernate sql 專為 Hibernate 定制
    <logger name="org.hibernate.type.descriptor.sql.BasicBinder"  level="TRACE" />
    <logger name="org.hibernate.type.descriptor.sql.BasicExtractor"  level="DEBUG" />
    <logger name="org.hibernate.SQL" level="DEBUG" />
    <logger name="org.hibernate.engine.QueryParameters" level="DEBUG" />
    <logger name="org.hibernate.engine.query.HQLQueryPlan" level="DEBUG" />-->

    <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="DEBUG"/>
    <logger name="java.sql.Connection" level="DEBUG"/>
    <logger name="java.sql.Statement" level="DEBUG"/>
    <logger name="java.sql.PreparedStatement" level="DEBUG"/>

    <!-- 日志輸出級別 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>
    <!--日志異步到數據庫 -->
    <!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">-->
    <!--&lt;!&ndash;日志異步到數據庫 &ndash;&gt;-->
    <!--<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">-->
    <!--&lt;!&ndash;連接池 &ndash;&gt;-->
    <!--<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
    <!--<driverClass>com.mysql.jdbc.Driver</driverClass>-->
    <!--<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>-->
    <!--<user>root</user>-->
    <!--<password>root</password>-->
    <!--</dataSource>-->
    <!--</connectionSource>-->
    <!--</appender>-->
</configuration>

自定義日志文件

1、springboot啟動的時候會自動加載日志的配置文件,默認使用的是self4j+logback,雖然springBoot為我們自動配置了默認的配置,但是我們還是需要自己定義配置文件,我們可以創建一個配置文件放置在resuorce文件夾下面,但是命名規則確實有一些區別,如下:

Logging System Customization
Logback logback-spring.xml, logback-spring.groovy, logback.xml, or logback.groovy
Log4j2 log4j2-spring.xml or log4j2.xml
JDK (Java Util Logging) logging.properties

2、總結的說就是,如果使用logback的日志,那么可以指定一個logback.xml放置在resource文件夾下,那么springBoot將會默認加載這個配置,直接覆蓋默認的配置。如果使用log4j這個日志框架,那么可以直接創建一個log4j.properties放置在resrouce文件夾下。如果使用log4j2這個日志,我們可以使用log4j2.xml這個日志文件放置在resoruce文件夾下。

日志框架的切換

1、上面的日志文件都是一個配置文件針對多個環境,但是如果我們想要使用profile的功能,比如開發環境使用一個日志配置文件,運行環境使用另外一個配置文件,那么此時就需要使用日志框架的profile功能,此時的命名規則就必須是logback-{profile}.xml,比如使用logback框架的時候,那么我們可以配置logback-dev.xml作用與開發環境,使用logback-spring.xml用于運行環境。

2、雖然懂得了命名規則,那么需要在日志的配置文件中指定切換語句,如下:

<springProfile name="staging">
    <!-- configuration to be enabled when the "staging" profile is active -->
</springProfile>

<springProfile name="dev | staging">
    <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
</springProfile>

<springProfile name="!production">
    <!-- configuration to be enabled when the "production" profile is not active -->
</springProfile>

程序中使用日志

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

private final Logger logger= LoggerFactory.getLogger(this.getClass());

SpringMVC的開發

1、如果想要開發springmvc模塊,只需要選中web模塊即可,默認的springBoot會自動為我們創建一些自動配置,不用自己一步一步的搭建springMVC框架。但是如果我們需要自己全面接管或者在原有的基礎上進行一些擴展的話,SpringBoot都提供了一些支持。

創建一個web模塊

1、創建項目,導入啟動器,如下:

        <!--導入web模塊-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--springBoot的測試模塊-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--導入這個處理器,在配置文件中將會自動提示-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>

        <!--熱啟動,保證每次修改,程序都會自動更新-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

引入靜態資源

webjars的引入

1、springMVC引入自動配置資源都是在org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration這個類中進行配置,因此靜態資源位置的映射也是在這個類中完成的,如下,即是配置靜態資源映射的方法

    @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
            CacheControl cacheControl = this.resourceProperties.getCache()
                    .getCachecontrol().toHttpCacheControl();
            //請求/webjars/**
            if (!registry.hasMappingForPattern("/webjars/**")) {
                customizeResourceHandlerRegistration(registry
                        .addResourceHandler("/webjars/**")
                        .addResourceLocations("classpath:/META-INF/resources/webjars/")
                        .setCachePeriod(getSeconds(cachePeriod))
                        .setCacheControl(cacheControl));
            }
            //添加 /**資源映射
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
            if (!registry.hasMappingForPattern(staticPathPattern)) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler(staticPathPattern)
                                .addResourceLocations(getResourceLocations(
                                        this.resourceProperties.getStaticLocations()))
                                .setCachePeriod(getSeconds(cachePeriod))
                                .setCacheControl(cacheControl));
            }
        }

2、通過上面的代碼可以知道任何/webjars/**這種請求的方式都會在classpath:/META-INF/resources/webjars/這個位置查找相關的靜態資源

3、webjars:是一種以jar包的方式引入靜態資源,比如引用jQuery、Bootstrap的文件,那么我們只需要引入對應的jar包即可訪問這些靜態資源,官方網址:https://www.webjars.org/

4、比如我們現在引入jquery的jar,如下:

    <!--引入jquery的jar-->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1-1</version>
        </dependency>

5、此時我們看到導入webjas的目錄結構,如下,自動配置的資源映射就是對應webjars下的資源位置,

image
1)、此時如果想要獲取jquery.js這個文件,那么可以通過`http://localhost:8080/webjars/jquery/3.3.1-1/jquery.js`這個url查詢到指定的文件,這個就是相對于上面springBoot自動配置的webjars的映射位置

其他靜態資源的引入

1、除了映入webjars這個靜態資源,我們還有自定義的css和js文件,那么我們也必須有一個位置放置這些資源,讓springBoot能夠訪問到

2、/**是用來訪問當前項目的任何資源,主要的就是靜態文件夾,默認映射的位置如下:

1)、classpath : 指定的是java和resources文件夾

2)、這寫文件夾都是存放靜態資源的,那么肯定會發生沖突,比如多個文件夾存放的靜態資源名稱是一樣的,那么我們該如何查找呢?

3)、這些文件夾是否順序訪問的,即是按照如下的優先級進行訪問的,如果上一級找到了,那么將會返回,下面的文件夾將不會查找
"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/",
"classpath:/public/" 

3、我們可以在classpath路徑下創建上面的四個文件夾用來存放靜態資源文件夾,這樣我們就可以訪問到這些資源了。如下:

image

4、此時我將slider.css這個靜態資源文件放置到static中,那么我們可以通過請求http://localhost:8080/slider.css,將可以訪問到這個資源,主要就是去上面的四個文件夾下查找文件,如果有這個文件,那么就返回即可。

配置首頁

1、在springBoot中,首頁也為我們自動配置了存放的位置

2、我們只需把首頁index.html放置在靜態資源文件夾下即可訪問,比如我們放一個index.html在static文件夾下,直接訪問http://localhost:8080/這個即可自動跳轉首頁

配置小圖標

1、我們可以放置一個favicon.ico圖片在靜態資源文件夾下,那么即可自動為我們的頁面配置上小圖標

自定義靜態資源存放位置

1、我們在全局配置文件中指定自己配置的資源存放位置,如下:

spring.resources.static-locations=classpath:/myStatic

2、一旦配置這個路徑,那么上面springBoot自動配置的路徑將會失效

模板引擎

1、sprintBoot不支持jsp,但是支持thymeleaf模板引擎,我們可以導入這個模板引擎

        <!--引入themleaf模板引擎-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

2、我們不需要指定版本號,在springBoot中已經為我們指定了默認的版本號,如下:

<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <thymeleaf-extras-data-attribute.version>2.0.1</thymeleaf-extras-data-attribute.version>
        <thymeleaf-extras-java8time.version>3.0.1.RELEASE</thymeleaf-extras-java8time.version>
        <thymeleaf-extras-springsecurity4.version>3.0.2.RELEASE</thymeleaf-extras-springsecurity4.version>
        <thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>

使用thymelefa

1、我們只需要將所有的html文件放在teamplate下,那么thymeleaf將會自動解析其中的文件

2、引入下面的約束將會自動提示語法:

<html lang="en" xmlns:th="http://www.thymeleaf.org">

語法

1、th: 這個是使用th任意屬性來替換原生屬性,比如替換id使用th:id,class使用th:class

2、<h1 th:text="${hello}">成功訪問</h1> :替換標簽體內的文本

3、表達式:

Simple expressions:
    Variable Expressions: ${...}
    Selection Variable Expressions: *{...}
    Message Expressions: #{...}
    Link URL Expressions: @{...}
    Fragment Expressions: ~{...}
    Literals
Text literals: 'one text' , 'Another one!' ,...
Number literals: 0 , 34 , 3.0 , 12.3 ,...
Boolean literals: true , false
Null literal: null
Literal tokens: one , sometext , main ,...
Text operations:
String concatenation: +
Literal substitutions: |The name is ${name}|
Arithmetic operations:
Binary operators: + , - , * , / , %
Minus sign (unary operator): -
Boolean operations:
Binary operators: and , or
Boolean negation (unary operator): ! , not
Comparisons and equality:
Comparators: > , < , >= , <= ( gt , lt , ge , le )
Equality operators: == , != ( eq , ne )
Conditional operators:
If-then: (if) ? (then)
If-then-else: (if) ? (then) : (else)
Default: (value) ?: (defaultvalue)
Special tokens:
Page 17 of 106No-Operation: _

springMVC的擴展

1、在springBoot中依賴mvc的自動配置肯定是不夠的,比如我們需要添加一個攔截器,那么肯定是需要自己配置的,此時我們就需要定義自己的配置類進行擴展功能。

2、擴展的意思是幾保留了mvc的自動配置,也使用了一些自定義的功能。

3、自動擴展的實現:

1)、定義一個配置類,使用`@Configuration`

2)、繼承`WebMvcConfigurationSupport`,這個類是一個抽象類,其中有實現springmvc的不同組件,如果需要那個組件,只需要實現其中的方法即可

3)、在這個類中實現其中的方法即可。

4、比如我們需要實現一個攔截器,那么我們需要創建一個攔截器類,如下:

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("使用攔截器");
        return true;
    }
}

5、我們需要在配置類中配置這個攔截器,如下:

@Configuration  //springBoot的自動配置類
public class MyConfig extends WebMvcConfigurationSupport {

        //添加一個映射視圖的組件,每次請求helloWorld都會映射到index.html
        @Override
        protected void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/helloWorld").setViewName("index");
        }

        //添加一個攔截器
        @Override
       protected void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(new                MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/helloWorld");
    }
}

全面接管SpringMVC

1、全面接管的意思就是不需要springBoot的自動配置,而是全部使用自定義的配置

2、要實現全面接管springMVC,那么只需要在上面的配置上添加一個@EnableWebMvc,如下:

@Configuration  //springBoot的自動配置類
@EnableWebMvc   //全面接管springMVC
public class MyConfig extends WebMvcConfigurationSupport {
    
}

指定日期格式

1、springBoot默認的可以轉換的日期格式:yyyy/MM/dd,那么我們可以在配置文件中改變這種配置格式,如下:

## 指定日期格式
spring.mvc.date-format=yyyy-MM-dd

2、一旦轉換了這種日期的格式,那么當用戶輸入的日期格式為上面的那種才會自動轉換成Date類型的數據,否則將會轉換失敗,出現異常

定制錯誤頁面

修改Tomcat的默認配置

1、在springBoot默認使用的是嵌入式的tomcat容器,我們可以在全局配置文件中修改默認的tomcat的配置。

2、如何修改tomcat 的默認配置?

1)、在全局的配置文件application.properties中修改配置即可,如下:

    1)、這些配置全部都是對應著`org.springframework.boot.autoconfigure.web.ServerProperties`這個類,Tomcat的配置對應著`org.springframework.boot.autoconfigure.web.ServerProperties.Tomcat`
## 指定編碼格式
## 如果需要修改tomcat的默認配置,我們需要修改server.tomcat.xxx
server.tomcat.uri-encoding=utf-8

## 指定端口號
## 如果需要修改server的默配置,我們需要修改server.xxxx
server.port=8080

注冊Servlet、Filter、Listener

1、在springBoot中如果需要用到Servlet、過濾器和監聽器,那么就需要自己配置

2、配置三大組件對應的類為:ServletRegistrationBeanFilterRegistrationBeanServletListenerRegistrationBean。我們只需要在自定義的配置類中將三個組件注冊到容器中即可

3、完成注冊三大組件

1)、創建自己的三大組件

2)、創建一個配置類,在其中創建注入三大組件即可,如下:
@Configuration   //指定這是一個配置類
public class MyWebConfig {

    //注冊自己的Servlet,在其中可以設置在配置文件中能夠設置的值
    @Bean   //將這個組件添加到容器中
    public ServletRegistrationBean registrationBean(){
        //構造方法,第一個參數指定的是自己的Servlet,第二個參數指定的是映射的路徑,是一個可變參數,可以指定多個參數
        ServletRegistrationBean bean=new ServletRegistrationBean(new MyServlet(),"/hello","/myFine");
        bean.setLoadOnStartup(1);
        return bean;
    }

    //注冊過濾器
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean bean=new FilterRegistrationBean();
        bean.setFilter(new MyFilter());  //設置自己的Filter
        bean.setUrlPatterns(Arrays.asList("/**"));  //設置攔截的路徑
        return bean;
    }

    //注冊監聽器
    @Bean
    public ServletListenerRegistrationBean servletListenerRegistrationBean(){
        ServletListenerRegistrationBean servletListenerRegistrationBean=new ServletListenerRegistrationBean<MyListener>(new MyListener());
        return servletListenerRegistrationBean;
    }
}

整合數據源

1、需要導入mysql的驅動程序

2、導入的依賴如下:

        <!--導入原生的jdbc啟動器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!--導入mysql的驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

3、我們可以在springBoot的配置文件中設置默認的mysql參數,如下:

## 配置Jdbc
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/jdbc
    driver-class-name: com.mysql.jdbc.Driver
    ## type用來指定使用什么數據連接池
    #type:

4、springBoot中默認支持的連接池都在org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration中展示出來,如下:

1)、`org.apache.tomcat.jdbc.pool.DataSource`

2)、`com.zaxxer.hikari.HikariDataSource`

3)、`org.apache.commons.dbcp2.BasicDataSource`

5、當然我們也是可以自定義自己的數據源,我們只需要在配置文件中使用spring-datasource.type這個配置即可

整合Druid數據源

0、https://www.cnblogs.com/niejunlei/p/5977895.html

1、導入依賴

        <!-- 添加數據庫連接池 druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

2、在全局配置文件中設置使用指定的數據源

# 數據庫訪問配置
# 主數據源,默認的
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/jdbc
spring.datasource.username=root
spring.datasource.password=root

3、配置數據源參數,下面只是設置了部分的參數,在全局配置文件中設置:

# 下面為連接池的補充設置,應用到上面所有數據源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取連接等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一個連接在池中最小生存的時間,單位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打開PSCache,并且指定每個連接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

4、自定義一個DruidConfig,主要用來配置Druid,如下:

@Configuration   //指定Druid的數據源的配置類
public class DruidConfig {

    //配置druid的參數,并且將其注入到容器中
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DruidDataSource druid(){
        return new DruidDataSource();
    }

    /**
     * 配置監控
     *  1、配置一個管理后臺的Servlet
     *  2、配置一個監控的filter
     */

    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean=new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //設置初始化參數
        Map<String,Object> initParams=new HashMap<>();
        initParams.put("loginUsername","admin");  //設置登錄的用戶名
        initParams.put("loginPassword","admin");  //設置登錄的密碼
        initParams.put("resetEnable","false");
//        initParams.put("allow","localhost");  //允許localhost訪問,默認是所有都能訪問
//        initParams.put("deny","IP地址");  //設置拒絕訪問的ip
        bean.setInitParameters(initParams);
        return bean;
    }

    //配置監控的Filter
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean bean=new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String,Object> initParams=new HashMap<>();
        initParams.put("exclusions","*.css,*.js,/druid/*");   //設置不攔截器的路徑
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/**"));
        return bean;
    }
}

整合Mybatis

1、添加mybatis的啟動器,如下:

    <!--導入mybatis的依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

2、只需要引入這個啟動器,那么springBoot就會自動導入如下的mybatis

    <mybatis.version>3.4.5</mybatis.version>
    <mybatis-spring.version>1.3.1</mybatis-spring.version>
    <spring-boot.version>1.5.6.RELEASE</spring-boot.version>

注解版

1、我們可以使用注解版本的mybatis,只需要創建一個Mapper即可。如下:

@Mapper   //表明這個是mapper接口,會自動掃描
public interface UserMapper {
    @Select("select * from t_user where user_id=#{userId}")
    User selectUser(Integer userId);

    //插入,自增主鍵返回
    @Options(useGeneratedKeys = true,keyProperty = "userId")
    @Insert("insert into t_user(name) values(#{name})")
    int insertUser(User user);
}

2、使用注解版,如果需要配置mybaits的一些參數,比如駝峰命名法等配置,那么我們可以自定義一個配置類,如下:

import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Mybatis的配置類
 */
@Configuration
public class MybatisConfig {

    //自定義一個定制器,在其中可以針對mybatis配置不同的參數,就相當于一個mybatis的主配置文件
    @Bean  //注入到容器中
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);  //開啟駝峰命名法
                //在其中還可以配置myabtis的其他配置
            }
        };
    }
}

3、除了自己配置自定義的配置類來指定mybatis的參數配置,我們還可以在全局配置文件中使用mybatis.來進行相關的配置,比如開啟駝峰命名,如下:

mybatis.configuration.map-underscore-to-camel-case=true

4、我們可以使用注解批量掃描mapper,這樣我們就不需要在每一個Mapper接口都添加@Mapper這個注解,我們只需要在主配置類中添加@MapperScan這個注解即可,如下:

//批量掃描com.tellwess.springbootserver.mappers這個包下面的所有mapper
@MapperScan(value ="com.tellwess.springbootserver.mappers")
@SpringBootApplication
public class SpringbootServerApplication {

配置文件

1、我們將所有的mapper對應的配置文件放在classpath:mapper/*.xml下面的,其中的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.tellwess.springbootserver.mappers.UserMapper" >

    <select id="selectUser" resultType="com.tellwess.springbootserver.entities.User">
      select * from t_user where user_id=#{userId}
    </select>

    <insert id="insertUser">
        insert  into t_user(name) values(#{name})
    </insert>

</mapper>

2、創建一個UserMapper.java,如下:

public interface UserMapper {

    User selectUser(Integer userId);


    int insertUser(User user);
}

3、在主配置類下創建添加批量掃描注解,將接口注入到容器中,如下:

//批量掃描com.tellwess.springbootserver.mappers這個包下面的所有mapper
@MapperScan(value ="com.tellwess.springbootserver.mappers")
@SpringBootApplication
public class SpringbootServerApplication {

4、在全局配置文件中設置*.xml配置文件的位置,讓springBoot能夠掃描到,如下:

## 配置mybatis的全局配置文件
mybatis.mapper-locations=classpath:mapper/*.xml
# 開啟駝峰命名
mybatis.configuration.map-underscore-to-camel-case=true
# 在其中還可以配置mybatis其他的配置

springBoot對事務的支持

1、在spring中我們如果需要添加事務,可能需要配置切面或者聲明式注解,但是在springBoot中我們只需要直接使用即可,一切都為我們自動配置了。

2、要想使用聲明式事務注解,那么需要導入spring.tx這個jar,其實這個jar在我們導入spring-boot-starter-jdbc的時候就已經為我們導入了,但是如果我們要是使用mybatis的話,那么只需要導入mybatis的場景啟動器即可,因為其中就已經包含了jdbc的場景啟動器,因此我們只需要導入mybatis的場景啟動器即可,如下:

    <!--導入mybatis的依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

3、在需要添加事務的類上添加一個注解即可@Transactional,如下:

@Transactional
@Service
public class UserServiceImpl implements UserService {}

自動熱部署

  • 每次修改代碼后都需要重新啟動程序,但是我們可以使用熱部署功能,只需要導入依賴即可。修改代碼完成后按住Ctrl+F9即可自動熱部署
        <!--熱部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>

SpringBoot對跨域的支持

//添加跨域的功能
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
//                        .allowedOrigins("http://192.168.1.97")
//                        .allowedMethods("GET", "POST")
//                        .allowCredentials(false).maxAge(3600);
                ;   //對所有的路徑都支持跨域的訪問
            }
        };
    }
  • 以上是針對全局配置的跨域,如果需要對某一個controller中的請求使用跨域,可以使用@CrossOrigin(origins = "http://192.168.1.97:8080", maxAge = 3600)這個注解標注在controller的類上,如下:
@CrossOrigin(origins = "http://192.168.1.97:8080", maxAge = 3600)
@RestController
public class IndexController{}

上傳文件大小的配置

  • 配置文件的方式:
#multipart upload 文件上傳
#限制一次上傳的單個文件的大小
spring.http.multipart.maxFileSize=10Mb
#限制一次上傳的所有文件的總大小
spring.http.multipart.maxRequestSize=10Mb

解決同一個tomcat中不能運行多個springBoot項目問題

# 每個項目的值必須不同
spring.jmx.default-domain=demo

總結

1、整合mybaits和數據源配置的所有依賴如下:

        <!--導入mysql的驅動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- 添加數據庫連接池 druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>

        <!--導入mybatis的依賴-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

springBoot配置文件能夠配置的全部配置

參考文檔

1、https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/

2、專欄

3、http://tengj.top/2017/04/24/springboot0/

4、http://www.ityouknow.com/spring-boot

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,363評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,497評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,305評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,962評論 1 311
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,727評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,193評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,257評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,411評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,945評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,777評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,978評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,519評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,216評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,657評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,960評論 2 373

推薦閱讀更多精彩內容