spring boot web
SpringBoot對靜態資源的對映規則
訪問網上的靜態資源對映
-
所有
/webjars/**
,都去classpath:/META-INF/resources/webjars/
找資源;webjars
檔案代表以jar包的形式去引入靜態資源,具體見webjars; -
webjars
使用方式很簡單,以jquery
引入為例:// pom.xml <!-- 引入jQuery -->在訪問的時候只需要寫**/webjars/資料夾下面的資源名稱即可 <dependency> <groupId></groupId> <artifactId>jquery</artifactId
訪問
http://localhost:8080/webjars/jquery/3.3.1/jquery.js
即可訪問到匯入靜態資原始檔夾中的jquery.js
檔案
訪問自身的靜態資原始檔對映
-
所有訪問
/**
訪問當前專案的靜態資源(css,img,js等檔案),都會去以下路徑查詢是否含有該檔案"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", // 習慣使用這個 **/src/main/resources/static/
訪問
http://localhost:8080/assets/css/signin.css
其實是訪問/src/main/resource/static/assets/css/signin.css
訪問首頁(歡迎頁)檔案對映
訪問/
預設顯示的頁面,也叫歡迎頁面,都會去靜態資源所在的路徑尋找index.html
檔案顯示出來
private Optional<Resource> getWelcomePage() {
String[] locations = getResourceLocations(this .resourceProperties.getStaticLocations());
return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
}
private Resource getIndexHtml(String location) {
return this.resourceLoader.getResource(location + "index.html");
}
複製程式碼
網頁tab圖示資源對映favicon.ico
訪問/favicon.ico
會直接對映到classpath:/public|static|resources/favicon.ico
SpringBoot訪問資料庫資料
classpath:/resources/
下的application.yml
檔案中配置資料庫連線資訊
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/jdbc
driver-class-name: com.mysql.cj.jdbc.Driver
複製程式碼
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
複製程式碼
- mysql驅動類mysql-connector-java版本在6以上,那麼 driver-class-name => com.mysql.cj.jdbc.Driver;
- mysql驅動類mysql-connector-java版本6以下,那麼 driver-class-name => com.mysql.jdbc.Driver;
預設資料來源:
SpringBoot建立預設DataSource時,規則如下:
- 優先尋找建立Tomcat連線池 // 預設先使用tomcat連線池
- 如果沒有Tomcat連線池,會查詢建立HikariCP
- 如果沒有HikariCP連線池,會查詢建立dbcp
- 如果沒有dbcp連線池,會查詢建立dbcp2
- 可以使用spring.datasource.type屬性指定連線池型別資料來源spring.datasource.type=org.apache.commons.dbcp.BasicDataSource
參考資料:
SpringBoot更換資料來源-druid資料來源(後臺監控sql及web請求)
-
引入druid,切換資料來源為druid資料來源
type: com.alibaba.druid.pool.DruidDataSource // 指定為druid資料來源 // 其他屬性 #上半區公共部分對應的是 org.springframework.boot.autoconfigure.jdbc.DataSourceProperties 中的屬性 #下半區屬性對應的是 com.alibaba.druid.pool.DruidDataSource 中的屬性,Spring Boot 預設是不注入不了這些屬性值的,需要自己繫結 #druid 資料來源專有配置 initialSize: 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:監控統計、log4j:日誌記錄、wall:防禦sql注入 #如果允許時報錯 java.lang.ClassNotFoundException: org.apache.log4j.Priority #則匯入log4j依賴即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 複製程式碼
-
配置druid資料來源自動裝配
// SpringBoot啟動類SpringBootDataJdbcApplication的同級資料夾中建立config.DruidConfig.java檔案 package com.dyh.www.springbootjdbc.config; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.util.Arrays; import java.util.HashMap; import java.util.Map; @Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource() { return new DruidDataSource(); } // 配置druid的監控 // 配置一個管理後臺的servlet @Bean public ServletRegistrationBean statViewServlet() { ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); Map<String,String> initParams = new HashMap<>(); initParams.put("loginUsername","admin"); initParams.put("loginPassword","123456"); initParams.put("allow",""); initParams.put("deny",""); bean.setInitParameters(initParams); return bean; } // 配置一個web監控的攔截filter @Bean public FilterRegistrationBean webStatFilter() { FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*"); // 靜態資源js,css檔案不攔截過濾 bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; } } 複製程式碼
SpringBoot整合mybatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
複製程式碼
註解版
// 這是操作資料庫的mapper
@Mapper // 資料庫與資料模型的對映註解,如果這裡沒有,則需要在SpringBootApplication啟動類上新增掃描全域性mapper的註解,並指定相應的掃描路徑
public interface DepartmentMapper {
// 資料庫的增刪改查sql介面資料對映
@Select("select * from department")
public List<Department> getDepartmentList();
@Select("select * from department where id=#{id}")
public Department getDepartmentById(Integer id);
@Delete("delete from department where id=#{id}")
public int deleteDepartmentById(Integer id);
@Options(useGeneratedKeys = true,keyProperty = "id") // 指定主鍵
@Insert("insert into department(departmentName) values(#{departmentName})")
public int insertDepartment(Department department);
@Update("update department set departmentName=#{departmentName} where id=#{id}")
public int updateDepartment(Department department);
}
// 這裡的 departmentName 對應資料庫的 departmentName 欄位
// 如果這裡的 department_name 相對應資料庫的 departmentName 欄位 轉換成駝峰命名方式,則可以增加轉換的自動配置
複製程式碼
import com.dyh.springbootmybatis.bean.Department;
import com.dyh.springbootmybatis.mapper.DepartmentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
// web API介面
@RestController
public class DepartmentController {
@Autowired
DepartmentMapper departmentMapper;
@RequestMapping(value = "/dept/{id}",method=RequestMethod.GET)
public Department getDepartmentById(@PathVariable("id") Integer id) {
return departmentMapper.getDepartmentById(id);
}
@RequestMapping(value = "/dept/list",method=RequestMethod.GET)
public List<Department> getDepartmentList() {
return departmentMapper.getDepartmentList();
}
@RequestMapping(value = "/dept",method = RequestMethod.GET)
public Department insertDepartment(Department department) {
departmentMapper.insertDepartment(department);
return department;
}
}
複製程式碼
-
轉換的自動配置
在config/資料夾下建立自定義mybatis的對映規則,給Spring容器新增一個ConfigurationCustomizer元件即可
@org.springframework.context.annotation.Configuration // 表明這是一個自動配置類 public class MybatisConfig { @Bean // 表明這是一個Spring容器元件 public ConfigurationCustomizer configurationCustomizer() { return new ConfigurationCustomizer() { @Override public void customize(Configuration configuration) { configuration.setMapUnderscoreToCamelCase(true); } }; } } 複製程式碼
-
@MapperScan(value = "com.dyh.springbootmybatis.mapper") // 這裡批量掃描mapper檔案,並且使用value指定路徑 @SpringBootApplication public class SpringBootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMybatisApplication.class,args); } } 複製程式碼
配置版
-
以Employee物件為例,首先定義資料實體類,與資料庫表字段一一對應
public class Employee { private Integer id; private String lastName; private String email; private Integer gender; private Integer departmentId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Integer getDepartmentId() { return departmentId; } public void setDepartmentId(Integer departmentId) { this.departmentId = departmentId; } } 複製程式碼
-
建立操作資料庫表介面的mapper,並統一在SpringBoot的主配置類中配置掃描mapper的路徑
import com.dyh.springbootmybatis.bean.Employee; import java.util.List; // API介面 public interface EmployeeMapper { public Employee getEmployeeById(Integer id); public List<Employee> getEmployeeList(); public Integer deleteEmployeeById(Integer id); } 複製程式碼
-
配置介面mapper與資料庫表操作對應的sql語句xml檔案
-
配置application.yml檔案指定xml檔案所在路徑
# 引入mybatis配置版檔案 mybatis: config-location: classpath:config/mybatis-config/global.xml mapper-locations: classpath:config/mybatis-config/mapper/*.xml 複製程式碼
-
配置全域性mybatis的配置檔案xml
<!-- global.xml檔案 --> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration> 複製程式碼
-
配置mybatis操作資料庫表的sql語句,與介面API的方法行成對映,具體配置見檔案
<!-- Employee.xml --> <!-- 介面API對映配置檔案 --> <?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.dyh.springbootmybatis.mapper.EmployeeMapper"> <!-- 唯一標識記號id值為API介面的對應方法 --> <select id="getEmployeeById" resultMap="employeeMap"> select * from employee where id = #{id} </select> <select id="getEmployeeList" resultMap="employeeMap"> select * from employee </select> <delete id="deleteEmployeeById"> delete from employee where id = #{id} </delete> <resultMap id="employeeMap" type="com.dyh.springbootmybatis.bean.Employee"> <!-- 資料庫表列欄位與實體類的例項屬性對映規則 --> <id property="id" column="id" /> <result property="lastName" column="lastName"/> <result property="gender" column="gender"/> <result property="email" column="email"/> <result property="departmentId" column="departmentId"/> </resultMap> </mapper> 複製程式碼
-
SpringBoot整合Jpa
目的
JPA是作為Spring Data一部分,用於簡化資料庫的curd和分頁列表獲取等資料操作的持久化框架,通過配置繼承封裝好資料操作的介面,為我們提供統一的API。
SpringBoot通過配置整合Jpa
JPA(ORM): Object Relational Mapping
-
編寫一個實體類(entity.User),將資料表的欄位和實體類的欄位進行對映,同時配置好對映規則(主鍵、自增、別名等)
import javax.persistence.*; // 使用JPA註解配置對映關係 @JsonIgnoreProperties(value = { "hibernateLazyInitializer","handler" }) // 標記不生成json物件的屬性 @Entity @Table(name = "tbl_user") // @Table指定該實體類的資料跟哪個資料表對應,如果省略,預設資料庫表名為該類名小寫user public class User { @Id // 這是一個主鍵 @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "last_name",length = 50) // 代表這是和資料庫表對應的一個列 private String lastName; @Column // 省略則預設列名就是屬性名 private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } 複製程式碼
-
編寫一個Dao介面來操作實體類對應的資料表,稱為Repository,包含常見資料的增刪改查,分頁等操作
import com.dyh.springbootjpa.entity.User; import org.springframework.data.jpa.repository.JpaRepository; // 繼承JpaRepository來繼承對資料的操作介面 public interface UserRepository extends JpaRepository<User,Integer> { } 複製程式碼
-
application.yml基本配置
# jpa關於sql相關配置 spring: jpa: hibernate: # 更新或建立資料表 ddl-auto: update # 在每次執行sql語句時打印出執行的sql語句 show-sql: true 複製程式碼
-
介面檔案
import com.dyh.springbootjpa.entity.User; import com.dyh.springbootjpa.repostitoy.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController public class UserController { @Autowired UserRepository userRepository; @RequestMapping(value = "/user/{id}",method = RequestMethod.GET) public User getUserById(@PathVariable("id") Integer id) { User user = userRepository.getOne(id); return user; } @RequestMapping(value = "/user/save",method = RequestMethod.GET) public User insertUser(User user) { User newUser = userRepository.save(user); return newUser; } @RequestMapping(value = "/user/all",method = RequestMethod.GET) public List<User> getUserList() { List<User> userList = userRepository.findAll(); return userList; } @RequestMapping(value = "/user/test",method = RequestMethod.GET) public String userTest() { long count = userRepository.count(); return "success:" + count; } } 複製程式碼
SpringBoot與日誌
日誌介紹
SpringBoot底層是Spring框架, Spring框架預設使用JCL作為日誌抽象層;
SpringBoot選用SLF4作為日誌抽象層,logback作為日誌實現層;
-
Jul - Java util logging
java.util.logging包下面的一款日誌框架,屬於JDK自帶的日誌實現;
-
Log4j
Apache的一個開源專案,可以不需要依賴第三方技術,直接記錄日誌;
-
Log4j2
log4j2和log4j是同一個作者開發,只不過log4j2是重新架構的一款日誌元件,拋棄了log4j的不足,以及吸取了優秀的logback的設計重新推出的一款新元件;
-
Jcl - Jakarta Commons Logging
jcl是apache公司開發的一個抽象日誌通用框架,本身不實現日誌記錄,但是提供了記錄日誌的抽象介面方法(info,debug,error…)。jcl預設使用jul列印日誌,如果專案依賴了log4j jar包,則使用log4j列印日誌;
-
Logback
Logback是由log4j創始人設計的一個開源日誌元件。LogBack被分為3個元件,logback-core,logback-classic 和 logback-access;
-
Slf4j - Simple Logging Facade for Java
Java的簡單日誌門面(SLF4J)用作各種日誌框架的簡單門面或抽象,像jul、logback和log4j等。SLF4J允許終端使用者在部署時插入所需的日誌框架,如果在專案中使用slf4j必須加一個依賴jar,即slf4j-api-xxx.jar。slf4j本身不記錄日誌,通過繫結器繫結一個具體的日誌框架來完成日誌記錄。
日誌抽象層 日誌實現層 Jcl、Slf4j、Jboss-logging Log4j、 Jul、Log4j2、Logback
SLF4j的使用
日誌記錄方法的呼叫,不應該直接呼叫日誌的實現類,而是應該呼叫日誌抽象層裡面的方法。
日誌統一的衝突解決方法(日誌框架適配圖)
自己的應用(slf4j+logback),spring(commons-logging),Hibernate(jboss-logging),Mybatis各框架都使用了不同的日誌框架,如何統一日誌記錄,使得所有的框架都使用slf4j輸出日誌,這是需要解決的問題。
將系統中其他日誌框架先排除掉,
用中間包替換掉原有被排除的日誌框架
再匯入slf4j實現統一的日誌輸出
SpringBoot使用的日誌框架
底層依賴的日誌框架
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<version>2.1.6.RELEASE</version>
<scope>compile</scope>
</dependency>
複製程式碼
依賴關係
總結:
SpringBoot使用slf4j+logback方式進行日誌記錄;
SpringBoot也把其他日誌換成了slf4j;
引入其他日誌框架,必須把本框架下的預設依賴的日誌框架移除掉(如果有的話);
// 低版本的Spring-core移除commons-logging日誌框架
// 高版本的Spring-core預設不整合commons-logging日誌框架
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
複製程式碼
如何在SpringBoot中使用日誌
-
日誌級別
Logger logger = LoggerFactory.getLogger(SpringbootLoggingApplication.class); // 日誌的級別 // 由低到高 trace < debug < info < warn < error // 在配置檔案中可以調整輸出的日誌級別,日誌就會在該級別及以上的高階別生效輸出日誌 logger.trace("這是trace資訊..."); logger.debug("這是debug資訊..."); // 本版本的SpringBoot預設輸出info級別及以上的日誌,配置檔案中沒有指定級別的話預設使用info級別,也叫root級別 - logging.level.root logger.info("這是info資訊..."); logger.warn("這是warn資訊..."); logger.error("這是error資訊..."); 複製程式碼
-
日誌輸出配置檔案—
application.properties
# application.properties #日誌輸出級別 logging.level.com.dyh = trace # 日誌輸出路徑 logging.path=/Users/dyh/IdeaProjects/mvn/springboot-logging # 日誌輸出至檔名,當然可以直接指定帶路徑的檔名,這樣日誌輸出路徑可不指定 logging.file=springboot-logging.log # 控制檯輸出日誌的格式 logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n # 檔案中輸出日誌的格式 logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} === [%thread] %-5level === %logger{50} === %msg%n 複製程式碼
-
日誌輸出格式說明
-
%clr(%5p) 表示輸出日誌的顏色(根據日誌級別)
-
%d 表示日期時間
-
%thread 表示執行緒名
-
%-5level 表示日誌級別level向左對齊顯示五個字元寬度
-
%logger{50} 表示日誌名字logger最長50個字元(日誌所在的包名),否則按句點分割
-
%msg 日誌輸出訊息
-
%n 換行符
-
-
日誌輸出配置檔案—
logback.xml || logback-spring.xml
雖然application.properties能進行日誌的配置,但是為了更方便、獨立地配置日誌,我們一般使用單獨的日誌配置檔案來進行日誌配置,如下:
Logging System Customization Logback logback-spring.xml
,logback-spring.groovy
,logback.xml
,orlogback.groovy
Log4j2 log4j2-spring.xml
orlog4j2.xml
JDK (Java Util Logging) logging.properties
SpringBoot
應用會預設識別logback.xml
檔案作為日誌的配置檔案,但是在logback.xml
中無法使用SpringBoot
配置的高階功能,如spring.profiles.active=dev
,即在不同環境中使用不同的日誌配置檔案,因此一般使用logback-spring.xml
作為指定的日誌配置檔案<!-- logback-spring.xml --> <?xml version="1.0" encoding="UTF-8"?> <configuration debug="false"> <!--自定義屬性,可以在之後使用;定義日誌檔案的儲存地址 勿在LogBack的配置中使用相對路徑--> <property name="LOG_HOME" value="/Users/dyh/IdeaProjects/mvn/springboot-logging" /> <!-- 控制檯輸出 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> <!--格式化輸出:%d表示日期,%thread表示執行緒名,%-5level:級別從左顯示5個字元寬度%msg:日誌訊息,%n是換行符,%yellow() 定義某個輸出資訊的顏色--> <pattern>%yellow(%d{yyyy-MM-dd HH:mm:ss.SSS}) %highlight([%thread] %-5level) %green(%logger{50}) - %cyan(%msg%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}/TestWeb-%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>10MB</MaxFileSize> </triggeringPolicy> </appender> <!-- 日誌輸出級別 --> <!--根據不同的環境輸出不同級別的日誌資訊--> <springProfile name="dev"> <!-- 在application.properties檔案中指定 spring.profiles.active=dev --> <root level="DEBUG"> <appender-ref ref="STDOUT" /> </root> </springProfile> <springProfile name="prod"> <!-- 在application.properties檔案中指定 spring.profiles.active=prod --> <root level="WARN"> <appender-ref ref="STDOUT" /> </root> </springProfile> </configuration> 複製程式碼
切換日誌框架
按照日誌適配圖進行切換即可