Springboot學習筆記

xiaodaopei發表於2020-12-29

Springboot學習筆記

1.基本配置

1.1springboot的入口類和@SpringBootApplication

POM檔案配置

<!--繼承springboot預設包-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
    </parent>

    <dependencies>
        <!--新增一個特殊的web應用依賴-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <defaultGoal>install</defaultGoal>
        <plugins>
            <!--編譯外掛-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
            <!--資源拷貝外掛-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!--打包外掛-->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

啟動程式

@SpringBootApplication
public class Application {

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

@SpringBootApplication是SpringBoot的核心註解,是一個組合註解,原始碼如下

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
        @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

    @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "exclude")
    Class<?>[] exclude() default {};

    @AliasFor(annotation = EnableAutoConfiguration.class, attribute = "excludeName")
    String[] excludeName() default {};

    @AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
    String[] scanBasePackages() default {};

    @AliasFor(annotation = ComponentScan.class, attribute = "basePackageClasses")
    Class<?>[] scanBasePackageClasses() default {};
}

1.2 關閉特定的自動配置

關閉特定的自動配置應該使用@SpringBootApplication註解的exclude引數

例:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

1.3 定製Banner

在springboot啟動的時候會有一個預設的啟動圖案

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v1.5.10.RELEASE)

在src/main/resources下新建一個banner.txt,通過http://patorjk.com/software/taag網站生成字元,如敲入simba1949,將網站生成的字元複製在banner.txt中,即可定製

這裡寫圖片描述

1.4 建立一個可執行的jar

新增打包外掛

<!--打包外掛-->
<plugin>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

命令執行:mvn package

會得到如下jar包

[INFO] Building jar: D:\Learn\IntelliJ IDEA\Workspace\springboot\springboot01\target\springboot01-1.0-SNAPSHOT.jar

在命令視窗輸入下面命令即可執行:

java -jar springboot01-1.0-SNAPSHOT.jar

1.5 SpringBoot的配置檔案

springboot使用一個全域性的配置檔案application.properties或者application.yml,放置在src/main/resources目錄下或者類路徑/config下

讀取properties檔案時,需要引入依賴包

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

在application.properties中新增如下資料

#配置對應的屬性
user.username:simba1949
user.age:hi,${user.username}!!!

@ConfigurationProperties註解讀取properties配置檔案,prefix=”user”

@Service
@ConfigurationProperties(prefix = "user")
public class UserServiceImpl implements UserService {

    private String username;
    private String say;

    @Override
    public void testProperties(){
        System.out.println(username);
        System.out.println("*******");
        System.out.println(say);
    }
    //需要屬性的settter方法
    public void setUsername(String username) {
        this.username = username;
    }
    public void setSay(String say) {
        this.say = say;
    }
}

1.6 屬性配置校驗

@NotNull
private Integer age;

執行時會報錯

這裡寫圖片描述

1.7 使用xml配置

@ImportResource({"classpath:ApplicationContext-tran.xml","classpath:ApplicationContext-dao.xml"})

2.日誌配置

在application.properties中配置日誌系統

#日誌配置
#日誌級別
logging.level.root=DEBUG
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=DEBUG
#輸出日誌名字
#logging.file=springboot001.log
#日誌輸出路徑
logging.path=D:/logs

3.Profile配置

Profile是Spring用來針對不同的環境進行不同的配置提供支援的,全域性Profile配置實用application-{profile}.properties。

通過在application.properties中設定spring.profiles.active=dev指定活動的Profile。

測試:生產環境埠為80,開發環境埠為8888

生產環境(application-prod.properties)配置如下:

server.port=80

開發環境(application-dev.properties)配置如下:

server.port=8888

application.properties配置:

spring.profiles.active=dev

執行如圖

這裡寫圖片描述

4.SpringBoot執行原理

5.http的編碼配置

SpringBoot內建的自動配置功能:http的編碼配置

在常規專案中配置http編碼的時候在web.xml裡配置一個filter

<filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

自動配置要滿足倆個條件

  1. 能配置CharacterEncodingFilter這個Bean
  2. 能配置encoding和forceEncoding這倆個引數

預設編碼方式為UTF-8,若修改可使用spring.http.encoding.charset=編碼;

設定forceEncoding,預設為true,若修改可使用spring.http.encoding.force=false

6.SSL配置

將生成的.keystore檔案複製到專案的根目錄下,然後再application.properties中配飾SSL

server.ssl.key-store=mykey.keystore
server.ssl.key-password=123456
server.ssl.key-store-type=JKS
server.ssl.key-alias=tomcat

這裡寫圖片描述

目錄結構

這裡寫圖片描述

7.SpringBoot的開發

7.1Tomcat配置

springboot預設內嵌Tomcat為servlet容器

配置servlet容器

 #配置程式埠,預設為8080
server.port=
#使用者會話session過期時間,以秒為單位
server.session.timeout=
#配置訪問路徑,預設為/
server.context-path=

配置tomcat

#配置tomcat編碼,預設為utf-8
server.tomcat.uri-encoding=

7.2Favicon配置

springboot預設開啟,關閉favicon在application.properties中配置即可

spring.mvc.favicon.enabled=false

定製Favicon

需要spring.mvc.favicon.enabled開啟,不配置預設開啟也可,將favicon.ico(檔名不能變動過)放置在src/main/resources/static下即可,執行效果

這裡寫圖片描述

目錄結構

這裡寫圖片描述

7.3整合springmvc

Json Rest實現

在springboot應用中,任何spring@RestController預設渲染為JSON響應

例如:

@GetMapping(value = "/list",produces = "application/json")
    @ResponseBody
    public List<User> list(){
        List<User> users = new ArrayList<User>();
        users.add(new User("李白","詩仙"));
        users.add(new User("杜甫","詩聖"));
        users.add(new User("王維","詩佛"));
        users.add(new User("白居易","詩魔"));
        users.add(new User("李賀","詩鬼"));
        users.add(new User("蘇軾","詩神"));
        return  users;
    }

這裡寫圖片描述

XML Rest實現

如果classpath下存在Jackson XML擴充套件(jackson-dataformat-xml) , 它會被用來渲染XML響應, 示例和JSON的非常相似。想要使用它, 只需為你的專案新增以下的依賴

<!--Jackson XML擴充套件包-->
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

例如:

@GetMapping(value = "/xml",produces = "application/xml")
    @ResponseBody
    public List<User> xml(){
        List<User> users = new ArrayList<User>();
        users.add(new User("李 白","詩仙"));
        users.add(new User("杜 甫","詩聖"));
        users.add(new User("王 維","詩佛"));
        users.add(new User("白居易","詩魔"));
        users.add(new User("李 賀","詩鬼"));
        users.add(new User("蘇 軾","詩神"));
        return  users;
    }

這裡寫圖片描述

SpringMVC檢視解析器配置

由於springboot已經不推薦使用jsp了,如果想使用jsp,需要手動引入相關依賴包。

<!-- jsp -->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
    <!-- <scope>provided</scope> -->
</dependency>
<!-- servlet 依賴 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <!--   <scope>provided</scope> -->
</dependency>
<!-- 新增 JSTL 支援 -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>

在application.properties配置檢視解析器

#檢視解析器
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp

7.4整合MyBatis

pom檔案新增依賴

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>6.0.6</version>
    <scope>runtime</scope>
</dependency>

mybatis在application.properties配置

#配置資料來源
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=19491001
#表示列印出sql語句
logging.level.com.shyroke.mapper=debug

#mybatis配置
mybatis.mapper-locations=classpath*:top/simba1949/mapper/*Mapper.xml
mybatis.type-aliases-package=top.simba1949.entity

還需要在Application配置@MapperScan(basePackages = “top.simba1949.mapper”)

@SpringBootApplication
//@mapperscan 指定被掃描的mapper所在的包路徑
@MapperScan(basePackages = "top.simba1949.mapper")
public class Application {

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

7.5 整合druid連線池

pom檔案新增依賴

<!--druid連線池-->
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.0.20</version>
</dependency>

在application.properties配置

#配置資料來源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=19491001
#表示列印出sql語句
logging.level.com.shyroke.mapper=debug

# 下面為連線池的補充設定,應用到上面所有資料來源中
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20

7.6 宣告式事務配置

7.6.1 基於註解

只需要在參與事務控制的方法上加上@Transactional註解即可。

@Transactional
@Override
public void addUser(User user) {
    int acount = userMapper.addUser(user);
}

7.6.2 基於xml配置檔案

引入aop依賴

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

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" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!-- 宣告式事務AOP配置 -->
    <aop:config>
        <aop:pointcut expression="execution(* top.simba1949.service.impl.*.*(..))" id="tranpointcut" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="tranpointcut" />
    </aop:config>
    <!-- 事務傳播特性配置 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT"
                       rollback-for="java.lang.Exception" />
            <!-- 查詢方法 -->
            <tx:method name="query*" read-only="true" />
            <tx:method name="select*" read-only="true" />
            <tx:method name="find*" read-only="true" />
        </tx:attributes>
    </tx:advice>
    <!-- 配置事務管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

配置匯入

@SpringBootApplication
//@mapperscan 指定被掃描的mapper所在的包路徑
@MapperScan(basePackages = "top.simba1949.mapper")
//@ImportResource 匯入事務配置
@ImportResource(value = "classpath:spring-aop.xml")
public class Application {

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

7.7 檔案上傳

配置檔案上傳屬性

#預設支援檔案上傳.
spring.http.multipart.enabled=true
#支援檔案寫入磁碟.
spring.http.multipart.file-size-threshold=0
# 最大支援檔案大小
spring.http.multipart.max-file-size=1Mb
# 最大支援請求大小
spring.http.multipart.max-request-size=10Mb

java程式碼

@RestController
@RequestMapping(value = "/upload")
public class UploadController {

    @PostMapping(value = "/image")
    public String image(@RequestParam(value = "userimage")MultipartFile file, HttpSession session) throws  Exception{
        //獲取upload目錄,不存在就建立
        String realPath = session.getServletContext().getRealPath("upload");
        File path = new File(realPath);
        if(!path.exists()){
            path.mkdirs();
        }
        //上傳
        file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
        return "http://localhost:8080/upload/"+file.getOriginalFilename();
    }
}

7.8 註冊攔截器

7.8.1自定義攔截器

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("preHandle-------------------------------");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle-------------------------------");
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion-------------------------------");
    }
}

7.8.2 註冊攔截器

@Configuration
public class WebRegister extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new UserInterceptor()).addPathPatterns("/add");
        super.addInterceptors(registry);
    }
}

7.9 springboot異常處理

@ControllerAdvice

該註解是spring2.3以後新增的一個註解,主要是用來Controller的一些公共的需求的低侵入性增強提供輔助,作用於@RequestMapping標註的方法上。

@ExceptionHandler

該註解是配合@ControllerAdvice一起使用的註解,自定義錯誤處理器,可自己組裝json字串,並返回到頁面。

@ControllerAdvice
public class ErrorHandlerController {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public String handleGlobalException(Exception e){
        System.out.println("0000000000000000000000------------------00000000000000000000000000"+e.getMessage());
        return "error";
    }
}

相關文章