springBoot初級入門

springBoot初級入門

獲取配置文件中的值@ConfigurationProperties

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

1、application.properties

2、application.yml

yml

1、key和value之間需要空格

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

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

4、大小寫敏感

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

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

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

6、List和Set的表示方法:

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

## 行內(nèi)的寫法:
pets: [dog,pig,cat]

7、Map<key,value>的寫法

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

8、舉例

1、JavaBean:

/**
 * ConfigurationProperties : 這個注解表示這個實體類的值來自于配置文件中,當(dāng)然包括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、添加一個依賴,將會在配置文件中自動提示

    <!--導(dǎo)入這個處理器,在配置文件中將會自動提示-->
        <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文件中的配置有很大的區(qū)別,如下:

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獲取文件中的信息的時候,默認(rèn)只能從默認(rèn)的配置文件中獲取信息,如果我們需要自己單獨定義一個配置文件,那么需要使用@PropertySource這個注解獲取其中的信息

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

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 : 這個注解表示這個實體類的值來自于配置文件中,當(dāng)然包括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這個注解能夠?qū)胱远x的配置文件并且獲取其中的值

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

@ImportSource

1、在springBoot中幾乎沒有配置文件,全部都是使用注解,那么我們?nèi)绻枰褂门渲梦募覀冊撊绾巫屵@個配置文件生效呢?

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、我們現(xiàn)在需要將其加入到IOC容器中,必須使用@ImportSource這個注解,我們需要在項目的主配置類上添加這個注解導(dǎo)入配置文件

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

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

配置類

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

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

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

配置文件占位符

1、可以使用隨機數(shù),如下:

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

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

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

多環(huán)境開發(fā)

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

properties

1、我們可以在創(chuàng)建不同的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可以使用---區(qū)分不同的文檔,只要在一個主配置文件application.yml中添加不同區(qū)域的文檔,即使表示不同的文件,如下:

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

---


## dev環(huán)境的配置
server:
  port: 8080
spring:
  profiles: dev

---

## prod環(huán)境的配置
server:
  port: 8088
spring:
  profiles: prod

配置文件加載位置

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

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

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

2、直接放在項目路徑下

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

4、直接放在classpath路徑下【創(chuàng)建項目的時候默認(rèn)位置】

3、classpth即是resource文件夾下

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

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

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

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

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

日志框架

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定義日志文件的存儲地址 一般存儲在服務(wù)器的文件夾中-->
    <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>
            <!--日志文件保留天數(shù)-->
            <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>
    <!--日志異步到數(shù)據(jù)庫 -->
    <!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">-->
    <!--&lt;!&ndash;日志異步到數(shù)據(jù)庫 &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啟動的時候會自動加載日志的配置文件,默認(rèn)使用的是self4j+logback,雖然springBoot為我們自動配置了默認(rèn)的配置,但是我們還是需要自己定義配置文件,我們可以創(chuàng)建一個配置文件放置在resuorce文件夾下面,但是命名規(guī)則確實有一些區(qū)別,如下:

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、總結(jié)的說就是,如果使用logback的日志,那么可以指定一個logback.xml放置在resource文件夾下,那么springBoot將會默認(rèn)加載這個配置,直接覆蓋默認(rèn)的配置。如果使用log4j這個日志框架,那么可以直接創(chuàng)建一個log4j.properties放置在resrouce文件夾下。如果使用log4j2這個日志,我們可以使用log4j2.xml這個日志文件放置在resoruce文件夾下。

日志框架的切換

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

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

<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的開發(fā)

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

創(chuàng)建一個web模塊

1、創(chuàng)建項目,導(dǎo)入啟動器,如下:

        <!--導(dǎo)入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>

        <!--導(dǎo)入這個處理器,在配置文件中將會自動提示-->
        <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>

引入靜態(tài)資源

webjars的引入

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

    @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/這個位置查找相關(guān)的靜態(tài)資源

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

4、比如我們現(xiàn)在引入jquery的jar,如下:

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

5、此時我們看到導(dǎo)入webjas的目錄結(jié)構(gòu),如下,自動配置的資源映射就是對應(yīng)webjars下的資源位置,

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

其他靜態(tài)資源的引入

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

2、/**是用來訪問當(dāng)前項目的任何資源,主要的就是靜態(tài)文件夾,默認(rèn)映射的位置如下:

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

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

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

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

image

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

配置首頁

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

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

配置小圖標(biāo)

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

自定義靜態(tài)資源存放位置

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

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

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

模板引擎

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

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

2、我們不需要指定版本號,在springBoot中已經(jīng)為我們指定了默認(rèn)的版本號,如下:

<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> :替換標(biāo)簽體內(nèi)的文本

3、表達(dá)式:

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、自動擴展的實現(xiàn):

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

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

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

4、比如我們需要實現(xiàn)一個攔截器,那么我們需要創(chuàng)建一個攔截器類,如下:

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、要實現(xiàn)全面接管springMVC,那么只需要在上面的配置上添加一個@EnableWebMvc,如下:

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

指定日期格式

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

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

2、一旦轉(zhuǎn)換了這種日期的格式,那么當(dāng)用戶輸入的日期格式為上面的那種才會自動轉(zhuǎn)換成Date類型的數(shù)據(jù),否則將會轉(zhuǎn)換失敗,出現(xiàn)異常

定制錯誤頁面

修改Tomcat的默認(rèn)配置

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

2、如何修改tomcat 的默認(rèn)配置?

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

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

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

注冊Servlet、Filter、Listener

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

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

3、完成注冊三大組件

1)、創(chuàng)建自己的三大組件

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

    //注冊自己的Servlet,在其中可以設(shè)置在配置文件中能夠設(shè)置的值
    @Bean   //將這個組件添加到容器中
    public ServletRegistrationBean registrationBean(){
        //構(gòu)造方法,第一個參數(shù)指定的是自己的Servlet,第二個參數(shù)指定的是映射的路徑,是一個可變參數(shù),可以指定多個參數(shù)
        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());  //設(shè)置自己的Filter
        bean.setUrlPatterns(Arrays.asList("/**"));  //設(shè)置攔截的路徑
        return bean;
    }

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

整合數(shù)據(jù)源

1、需要導(dǎo)入mysql的驅(qū)動程序

2、導(dǎo)入的依賴如下:

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

        <!--導(dǎo)入mysql的驅(qū)動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

3、我們可以在springBoot的配置文件中設(shè)置默認(rèn)的mysql參數(shù),如下:

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

4、springBoot中默認(rèn)支持的連接池都在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、當(dāng)然我們也是可以自定義自己的數(shù)據(jù)源,我們只需要在配置文件中使用spring-datasource.type這個配置即可

整合Druid數(shù)據(jù)源

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

1、導(dǎo)入依賴

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

2、在全局配置文件中設(shè)置使用指定的數(shù)據(jù)源

# 數(shù)據(jù)庫訪問配置
# 主數(shù)據(jù)源,默認(rèn)的
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、配置數(shù)據(jù)源參數(shù),下面只是設(shè)置了部分的參數(shù),在全局配置文件中設(shè)置:

# 下面為連接池的補充設(shè)置,應(yīng)用到上面所有數(shù)據(jù)源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置獲取連接等待超時的時間
spring.datasource.maxWait=60000
# 配置間隔多久才進行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒
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的數(shù)據(jù)源的配置類
public class DruidConfig {

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

    /**
     * 配置監(jiān)控
     *  1、配置一個管理后臺的Servlet
     *  2、配置一個監(jiān)控的filter
     */

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

    //配置監(jiān)控的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/*");   //設(shè)置不攔截器的路徑
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/**"));
        return bean;
    }
}

整合Mybatis

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

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

2、只需要引入這個啟動器,那么springBoot就會自動導(dǎo)入如下的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,只需要創(chuàng)建一個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的一些參數(shù),比如駝峰命名法等配置,那么我們可以自定義一個配置類,如下:

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配置不同的參數(shù),就相當(dāng)于一個mybatis的主配置文件
    @Bean  //注入到容器中
    public ConfigurationCustomizer configurationCustomizer(){
        return new ConfigurationCustomizer() {
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
                configuration.setMapUnderscoreToCamelCase(true);  //開啟駝峰命名法
                //在其中還可以配置myabtis的其他配置
            }
        };
    }
}

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

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對應(yīng)的配置文件放在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、創(chuàng)建一個UserMapper.java,如下:

public interface UserMapper {

    User selectUser(Integer userId);


    int insertUser(User user);
}

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

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

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

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

springBoot對事務(wù)的支持

1、在spring中我們?nèi)绻枰砑邮聞?wù),可能需要配置切面或者聲明式注解,但是在springBoot中我們只需要直接使用即可,一切都為我們自動配置了。

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

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

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

@Transactional
@Service
public class UserServiceImpl implements UserService {}

自動熱部署

  • 每次修改代碼后都需要重新啟動程序,但是我們可以使用熱部署功能,只需要導(dǎo)入依賴即可。修改代碼完成后按住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)這個注解標(biāo)注在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

總結(jié)

1、整合mybaits和數(shù)據(jù)源配置的所有依賴如下:

        <!--導(dǎo)入mysql的驅(qū)動-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

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

        <!--導(dǎo)入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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,970評論 6 342
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,981評論 19 139
  • 個人專題目錄[http://www.lxweimin.com/u/2a55010e3a04] 一、Spring B...
    Java及SpringBoot閱讀 2,839評論 1 25
  • 前言:學(xué)習(xí)SpringBoot不應(yīng)該直接就是開始使用SpringBoot,如果直接拿來用肯定會有很多人不是很明白特...
    CoderZS閱讀 74,856評論 10 217
  • 今天是七夕,避免不了情侶的秀恩愛和單身狗的感傷。今天來談?wù)勛屓擞窒灿直膼矍椤? 大學(xué)的時候談過一個...
    甜甜甜甜大甜橙閱讀 282評論 0 0