- springboot
- 回顧spring
- springboot
- springboot搭建(新聞為例)
- springboot中的配置文件
- spring集成jdbc,mybatis,阿里巴巴數據源
- **SpringBoot 集成日志功能**(了解)
- 常用日志組件
- 日志級別
- springboot統一異常處理
springboot
回顧spring
spring是一個輕量級的IOC和AOP的一站式框架,為簡化企業級應用開發而生.
優點:
? 輕量級
? IOC
? AOP
解耦 (代碼之間的耦合度降低了, 例如IOC,由框架創建管理對象, AOP可以將業務代碼和非業務代碼分離)
一站式 (數據訪問層 數據連接對象管理,mybatis,事務), 對web層的Servlet進行封裝
開源
很方便的集成其他的框架
缺點:
1.配置是重量級的,而且大量是模板化配置
<!--屬于很啰嗦的模板化配置--><!--開啟aop自動代理--><aop:aspectj-autoproxy></aop:aspectj-autoproxy><!-- 開啟注解事務管理 --><tx:annotation-driven transaction-manager="transactionManager"/><!--開啟web層的注解--><mvc:annotation-driven></mvc:annotation-driven>
2.項目中需要導入很多相關的依賴坐標(例如 json組件, 跨域過濾器…)
springboot
springboot
是在spring的基礎上,對spring應用的搭建進行簡化,基于約定大于配置
的思想(大家公認的做法,那么框架也就默認把一些功能直接實現了,例如我們現在都用注解開發),可以創建一個企業級應用程序, 內嵌服務器(tomcat),有量大核心功能:起步依賴
: 當我們使用spring基本的依賴時, 自動就會將相關的依賴導入進來。自動配置
: spring啟動時,可以根據我們項目中配置的相關依賴,自動加載配置.
? Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".
? Wetake an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need minimal Spring configuration
springboot搭建(新聞為例)
1.創建一個普通的maven項目

2.配置 pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>SpringBoot</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><!--指定 jdk 版本--><java.version>1.8</java.version></properties><!--依賴的父級工程--><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.6</version><relativePath/></parent><!--添加基本的 springweb 依賴--><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><!--打包插件--><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><version>2.6.6</version></plugin></plugins></build></project>
創建啟動類NewsApplication
package org.example;import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;
@SpringBootApplicationpublic class NewsApplication {public static void main(String[] args) {SpringApplication.run(NewsApplication.class);}
}
3.創建自定義的處理器(web包)
@RestController
@RequestMapping(path = "/loginCtl")
public class LoginController {@RequestMapping(path = "/login")public String login(){System.out.println("aaaaaaaaaaaaa");return "success";}
}
啟動mian
啟動成功!!!
tips:可以在Ascii藝術字實現個性化Spring Boot啟動banner圖案,輕松修改更換banner.txt文件內容,收集了豐富的banner藝術字和圖,并且支持中文banner下載,讓你的banner好玩兒更有意思。-bootschool.net網站下載啟動時候的圖案
4.訪問
? ip:端口/處理地址/方法地址
springboot中的配置文件
springboot中的配置文件,嚴格意義上不是配置文件, 是用來存儲配置參數的文件(里面放的是參數值).
配置文件有兩種格式:
-
屬性文件 .properties
鍵 = 值 server.port=8089 spring.datasource.driver-class-name= spring.datasource.url= spring.activemq.password= spring.datasource.username=
2.yml
#配置服務器端口
server:port: 8088spring:datasource:driver-class-name:url:username:password:
spring集成jdbc,mybatis,阿里巴巴數據源
1.導入依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId>
</dependency><!--mysql-->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.16</version>
</dependency><!-- 阿里巴巴數據源 -->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.10</version>
</dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.1.4</version>
</dependency>
2.application.yml配置文件(在resource
文件夾內)
# 端口號
server:port: 8080
# 數據庫配置
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/spring_demo?serverTimezone=Asia/Shanghaiusername: rootpassword: root# 使用阿里巴巴的druid連接池type: com.alibaba.druid.pool.DruidDataSourcedruid:initial-size: 5min-idle: 5max-active: 20max-wait: 60000
# mybatis配置
mybatis:# 掃描mapper包type-aliases-package: org.example.model# mapper.xml文件位置mapper-locations: classpath:mapper/*Mapper.xml# 加載全局配置文件configuration:# 駝峰命名map-underscore-to-camel-case: true# 自動加載mapper.xmlcache-enabled: true# 打印sql語句log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
對啟動類進行配置@MapperScan("org.example.dao") // This line is used to scan the DAO package for SQL mappers
package org.example;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.SpringApplication;// This is the main class of the News Application
@SpringBootApplication
@MapperScan("org.example.dao") // This line is used to scan the DAO package for SQL mapperspublic class NewsApplication {public static void main(String[] args) {SpringApplication.run(NewsApplication.class);}
}
3.創建服務類
package org.example.service;import org.example.dao.LoginDao;
import org.example.model.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;@Service
// 這個注解表示這是一個服務類,并且在事務中進行操作,如果出現異常,則回滾事務
@Transactional(rollbackFor = Exception.class)
public class LoginService {@AutowiredLoginDao loginDao;public Admin login(Admin admin) {return loginDao.login(admin);}
}
編寫LoginController類
package org.example.web;import org.example.model.Admin;
import org.example.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/loginCtl")
public class LoginController {@AutowiredLoginService loginService;@RequestMapping(path = "/login")public Admin login(@RequestBody Admin admin){Admin admin1 = loginService.login(admin);System.out.println("aaaaaaaaaaaaa");return admin1;}}
使用ApiPost測試
成功!!
最終文件結構
SpringBoot 集成日志功能(了解)
日志?
日志是程序中重要組成部分,可以監測程序運行軌跡, 記錄參數值的變化.尤其是生產環境中非常必要, 通過日志文件可以快速的定位到問題.
什么時候使用日志
答:實際生產環境
常用日志組件
slf4j(Simple Logging Facade for Java)
commons-logging
Log4J
Log4J2
Logback
JUL(Java Utils Logging)
日志級別
從低到高:debug<info<warn<error
logging:level:org.example: infofile:name: D:/log/log.log#類里面配置Logger對象 private static Logger logger = LoggerFactory.getLogger(LoginController.class);logger.debug("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());
logger.info("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());
logger.warn("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());
logger.error("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());
保存位置如下
在LoginController添加Logger對象
package org.example.web;import org.example.model.Admin;
import org.example.service.LoginService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/loginCtl")
public class LoginController {private static Logger logger = LoggerFactory.getLogger(LoginController.class);@AutowiredLoginService loginService;@RequestMapping(path = "/login")public Admin login(@RequestBody Admin admin) {logger.debug("input account:{},paasord:{}", admin.getAccount(), admin.getPassword());logger.info("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());logger.warn("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());logger.error("input account:{},paasord:{}",admin.getAccount(),admin.getPassword());/*@RequestBody 作用是將請求體中的json數據綁定到Admin對象中*/Admin admin1 = loginService.login(admin);System.out.println("aaaaaaaaaaaaa");return admin1;}}
項目中統一異常打印
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package org.example.util;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;@Component
@Aspect
public class LogAspect {private static Logger logger = LoggerFactory.getLogger(LogAspect.class);@Before("execution(public * org.example.web.*.*(..))")public void savelog(JoinPoint joinPoint) {ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();// 記錄下請求內容logger.info("HTTP_METHOD :{} ", request.getMethod());logger.info("IP : {}", request.getRemoteAddr());//客戶端 ipObject[] objs = joinPoint.getArgs(); //獲取方法參數logger.info(Arrays.toString(objs));}
}
springboot統一異常處理
/*全局統一的異常處理類*/
@RestControllerAdvice
public class GlobalExceptionHandler {private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);/*** 異常處理*/@ExceptionHandler(Exception.class)public Result globalException(Exception e) {Result commonResult = new Result(500,"系統忙:"+e.getMessage(),null);logger.info("Exception : "+e.getMessage());//向日志文件打印信息return commonResult;//向前端用戶響應信息}
}
統一日志打印,統一異常處理都是AOP的實際使用場景, spring中的事務管理也是AOP的使用場景
到此,后端最基本的功能搭建完成.