中英文企業(yè)網(wǎng)站怎么做信息流廣告代理商
一、SpringBoot簡(jiǎn)介
1.1 SpringBoot特點(diǎn)
- 為基于Spring的開發(fā)提供更快的入門體驗(yàn)
- 開箱即用,沒有代碼生成,也無需XML配置。同時(shí)也可以修改默認(rèn)值來滿足特定的需求
- 提供了一些大型項(xiàng)目中常見的非功能性特性,如嵌入式服務(wù)器、安全、指標(biāo),健康檢測(cè)、外部配置等
- SpringBoot不是對(duì)Spring功能上的增強(qiáng),而是提供了一種快速使用Spring的方式
1.2SpringBoot的核心功能
-
起步依賴
起步依賴本質(zhì)上是一個(gè)Maven項(xiàng)目對(duì)象模型(Project Object Model,POM),定義了對(duì)其他庫(kù)的傳遞依賴,這些東西加在一起即支持某項(xiàng)功能。
簡(jiǎn)單的說,起步依賴就是將具備某種功能的坐標(biāo)打包到一起,并提供一些默認(rèn)的功能。
-
自動(dòng)配置
Spring Boot的自動(dòng)配置是一個(gè)運(yùn)行時(shí)(更準(zhǔn)確地說,是應(yīng)用程序啟動(dòng)時(shí))的過程,考慮了眾多因素,才決定Spring配置應(yīng)該用哪個(gè),不該用哪個(gè)。該過程是Spring自動(dòng)完成的。
1.3環(huán)境準(zhǔn)備
- jdk1.8:Spring Boot 推薦jdk1.7及以上;java version “1.8.0_151”
- maven3.x:maven 3.3以上版本;Apache Maven 3.3.9
- IntelliJIDEA2018:IntelliJ IDEA2018.2.5 x64、STS
- SpringBoot 2.0.1.RELEASE
二、SpringBoot快速入門
2.1 代碼實(shí)現(xiàn)
2.1.1 創(chuàng)建Maven工程
使用idea工具創(chuàng)建一個(gè)maven工程,該工程為普通的java工程即可
2.1.2 添加SpringBoot的起步依賴
SpringBoot要求,項(xiàng)目要繼承SpringBoot的起步依賴spring-boot-starter-parent
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.1.RELEASE</version>
</parent>
SpringBoot要集成SpringMVC進(jìn)行Controller的開發(fā),所以項(xiàng)目要導(dǎo)入web的啟動(dòng)依賴
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>
</dependencies>
2.1.3 編寫SpringBoot引導(dǎo)類
要通過SpringBoot提供的引導(dǎo)類起步SpringBoot才可以進(jìn)行訪問
package com.zhangcc;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class MySpringBootApplication {public static void main(String[] args) {SpringApplication.run(MySpringBootApplication.class);}
}
2.1.4 編寫Controller
在引導(dǎo)類MySpringBootApplication同級(jí)包或者子級(jí)包中創(chuàng)建QuickStartController
package com.zhangcc.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;@Controller
public class QuickStartController {@RequestMapping("/quick")@ResponseBodypublic String quick(){return "SpringBoot 訪問成功!";}
}
2.1.5 測(cè)試
執(zhí)行SpringBoot起步類的主方法,控制臺(tái)打印日志如下:
. ____ _ __ _ _/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \\\/ ___)| |_)| | | | | || (_| | ) ) ) )' |____| .__|_| |_|_| |_\__, | / / / /=========|_|==============|___/=/_/_/_/:: Spring Boot :: (v2.0.1.RELEASE)2019-02-21 16:45:37.861 INFO 4876 --- [ main] com.zhangcc.MySpringBootApplication : Starting MySpringBootApplication on DESKTOP-EHU9NMQ with PID 4876 (D:\IDEWorkspace\SpringBoot_Quick\target\classes started by dell in D:\IDEWorkspace\SpringBoot_Quick)
2019-02-21 16:45:37.863 INFO 4876 --- [ main] com.zhangcc.MySpringBootApplication : No active profile set, falling back to default profiles: default
2019-02-21 16:45:37.893 INFO 4876 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@5db45159: startup date [Mon Feb 21 16:45:37 CST 2022]; root of context hierarchy
2019-02-21 16:45:38.540 INFO 4876 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-02-21 16:45:38.554 INFO 4876 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-02-21 16:45:38.554 INFO 4876 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.29
2019-02-21 16:45:38.557 INFO 4876 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [E:\development\Java\jdk1.8.0_151\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;E:\development\Java\jdk1.8.0_151\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;E:\development\TortoiseSVN\bin;C:\WINDOWS\System32\OpenSSH\;C:\Users\dell\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Bandizip\;.]
2019-02-21 16:45:38.621 INFO 4876 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-02-21 16:45:38.621 INFO 4876 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 730 ms
2019-02-21 16:45:38.698 INFO 4876 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2019-02-21 16:45:38.701 INFO 4876 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-02-21 16:45:38.701 INFO 4876 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-02-21 16:45:38.701 INFO 4876 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-02-21 16:45:38.701 INFO 4876 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2019-02-21 16:45:38.761 INFO 4876 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-02-21 16:45:38.889 INFO 4876 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@5db45159: startup date [Mon Feb 21 16:45:37 CST 2022]; root of context hierarchy
2019-02-21 16:45:38.922 INFO 4876 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/quick]}" onto public java.lang.String com.zhangcc.controller.QuickStartController.quick()
2019-02-21 16:45:38.925 INFO 4876 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-02-21 16:45:38.925 INFO 4876 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-02-21 16:45:38.938 INFO 4876 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-02-21 16:45:38.938 INFO 4876 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-02-21 16:45:39.024 INFO 4876 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2019-02-21 16:45:39.050 INFO 4876 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-02-21 16:45:39.053 INFO 4876 --- [ main] com.zhangcc.MySpringBootApplication : Started MySpringBootApplication in 1.426 seconds (JVM running for 2.402)
通過日志發(fā)現(xiàn),Tomcat started on port(s): 8080 (http) with context path ‘’
tomcat已經(jīng)起步,端口監(jiān)聽8080,web應(yīng)用的虛擬工程名稱為空
打開瀏覽器訪問url地址為:http://localhost:8080/quick
2.2 快速入門解析
2.2.1 SpringBoot代碼解析
- @SpringBootApplication:標(biāo)注SpringBoot的啟動(dòng)類,該注解具備多種功能(后面詳細(xì)剖析)
- SpringApplication.run(MySpringBootApplication.class) 代表運(yùn)行SpringBoot的啟動(dòng)類,參數(shù)為SpringBoot啟動(dòng)類的字節(jié)碼對(duì)象
2.2.2 SpringBoot工程熱部署
我們?cè)陂_發(fā)中反復(fù)修改類、頁(yè)面等資源,每次修改后都是需要重新啟動(dòng)才生效,這樣每次啟動(dòng)都很麻煩,浪費(fèi)了大量的時(shí)間,我們可以在修改代碼后不重啟就能生效,在 pom.xml 中添加如下配置就可以實(shí)現(xiàn)這樣的功能,我們稱之為熱部署。
<!--熱部署配置-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId>
</dependency>
注意:IDEA進(jìn)行SpringBoot熱部署失敗原因
出現(xiàn)這種情況,并不是熱部署配置問題,其根本原因是因?yàn)镮ntellij IEDA默認(rèn)情況下不會(huì)自動(dòng)編譯,需要對(duì)IDEA進(jìn)行自動(dòng)編譯的設(shè)置,如下:
然后 Shift+Ctrl+Alt+/,選擇Registry
2.2.3 使用idea快速創(chuàng)建SpringBoot項(xiàng)目
通過idea快速創(chuàng)建的SpringBoot項(xiàng)目的pom.xml中已經(jīng)導(dǎo)入了我們選擇的web的起步依賴的坐標(biāo)
<?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>com.zhangcc</groupId><artifactId>springboot_quick2</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>springboot_quick2</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.1.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>9</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
可以使用快速入門的方式創(chuàng)建Controller進(jìn)行訪問,此處不再贅述
三、SpringBoot的配置文件
3.1 SpringBoot配置文件類型
3.1.1 SpringBoot配置文件類型和作用
SpringBoot是基于約定的,所以很多配置都有默認(rèn)值,但如果想使用自己的配置替換默認(rèn)配置的話,就可以使用application.properties或者application.yml(application.yaml)進(jìn)行配置。
SpringBoot默認(rèn)會(huì)從Resources目錄下加載application.properties或application.yml(application.yaml)文件
其中,application.properties文件是鍵值對(duì)類型的文件,之前一直在使用,所以此處不在對(duì)properties文件的格式進(jìn)行闡述。除了properties文件外,SpringBoot還可以使用yml文件進(jìn)行配置,下面對(duì)yml文件進(jìn)行講解。
3.1.2 application.yml配置文件
3.1.2.1 yml配置文件簡(jiǎn)介
YML文件格式是YAML (YAML Aint Markup Language)編寫的文件格式,YAML是一種直觀的能夠被電腦識(shí)別的的數(shù)據(jù)數(shù)據(jù)序列化格式,并且容易被人類閱讀,容易和腳本語言交互的,可以被支持YAML庫(kù)的不同的編程語言程序?qū)?#xff0c;比如: C/C++, Ruby, Python, Java, Perl, C#, PHP等。YML文件是以數(shù)據(jù)為核心的,比傳統(tǒng)的xml方式更加簡(jiǎn)潔。
YML文件的擴(kuò)展名可以使用.yml或者.yaml。
3.1.2.2 yml配置文件的語法
3.1.2.2.1 配置普通數(shù)據(jù)
-
語法: key: value(表示一對(duì)鍵值對(duì),空格必須要有),以空格的縮進(jìn)來控制層級(jí)關(guān)系;只要是左對(duì)齊的一列數(shù)據(jù),都是同一層級(jí)的
-
示例代碼:
-
name: haohao
-
注意:value之前有一個(gè)空格
3.1.2.2.2 配置對(duì)象數(shù)據(jù)
-
語法:
? key:
? key1: value1
? key2: value2
? 或者:
? key: {key1: value1,key2: value2}
-
示例代碼:
-
person:name: haohaoage: 31addr: beijing#或者person: {name: haohao,age: 31,addr: beijing}
-
注意:key1前面的空格個(gè)數(shù)不限定,在yml語法中,相同縮進(jìn)代表同一個(gè)級(jí)別
3.1.2.2.3 配置Map數(shù)據(jù)
同上面的對(duì)象寫法
3.1.2.2.4 配置數(shù)組(List、Set)數(shù)據(jù)
-
語法:
? key:
? - value1
? - value2
或者:
? key: [value1,value2]
-
示例代碼:
-
city:- beijing- tianjin- shanghai- chongqing#或者city: [beijing,tianjin,shanghai,chongqing]#集合中的元素是對(duì)象形式 student:- name: zhangsanage: 18score: 100- name: lisiage: 28score: 88- name: wangwuage: 38score: 90
-
注意:value1與之間的 - 之間存在一個(gè)空格
3.1.3 SpringBoot配置信息的查詢
上面提及過,SpringBoot的配置文件,主要的目的就是對(duì)配置信息進(jìn)行修改的,但在配置時(shí)的key從哪里去查詢呢?我們可以查閱SpringBoot的官方文檔
文檔URL:https://docs.spring.io/spring-boot/docs/2.0.1.RELEASE/reference/htmlsingle/#common-application-properties
常用的配置摘抄如下:
# QUARTZ SCHEDULER (QuartzProperties)
spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode.
spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to use to initialize the database schema.
spring.quartz.job-store-type=memory # Quartz job store type.
spring.quartz.properties.*= # Additional Quartz Scheduler properties.# ----------------------------------------
# WEB PROPERTIES
# ----------------------------------------# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080 # Server HTTP port.
server.servlet.context-path= # Context path of the application.
server.servlet.path=/ # Path of the main dispatcher servlet.# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.# JACKSON (JacksonProperties)
spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`.# SPRING MVC (WebMvcProperties)
spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet.
spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
spring.mvc.view.prefix= # Spring MVC view prefix.
spring.mvc.view.suffix= # Spring MVC view suffix.# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.password= # Login password of the database.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.# JEST (Elasticsearch HTTP client) (JestProperties)
spring.elasticsearch.jest.password= # Login password.
spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use.
spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use.
spring.elasticsearch.jest.read-timeout=3s # Read timeout.
spring.elasticsearch.jest.username= # Login username.
我們可以通過配置application.poperties 或者 application.yml 來修改SpringBoot的默認(rèn)配置
例如:
application.properties文件
server.port=8888
server.servlet.context-path=demo
application.yml文件
server:port: 8888servlet:context-path: /demo
3.2 配置文件與配置類的屬性映射方式
3.2.1 使用注解@Value映射
我們可以通過@Value注解將配置文件中的值映射到一個(gè)Spring管理的Bean的字段上
例如:
application.properties配置如下:
person:name: zhangsanage: 18
或者,application.yml配置如下:
person:name: zhangsanage: 18
實(shí)體Bean代碼如下:
@Controller
public class QuickStartController {@Value("${person.name}")private String name;@Value("${person.age}")private Integer age;@RequestMapping("/quick")@ResponseBodypublic String quick(){return "springboot 訪問成功! name="+name+",age="+age;}}
3.2.2 使用注解@ConfigurationProperties映射
通過注解@ConfigurationProperties(prefix=“配置文件中的key的前綴”)可以將配置文件中的配置自動(dòng)與實(shí)體進(jìn)行映射
application.properties配置如下:
person:name: zhangsanage: 18
或者,application.yml配置如下:
person:name: zhangsanage: 18
實(shí)體Bean代碼如下:
@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {private String name;private Integer age;@RequestMapping("/quick")@ResponseBodypublic String quick(){return "springboot 訪問成功! name="+name+",age="+age;}public void setName(String name) {this.name = name;}public void setAge(Integer age) {this.age = age;}
}
注意:使用@ConfigurationProperties方式可以進(jìn)行配置文件與實(shí)體字段的自動(dòng)映射,但需要字段必須提供set方法才可以,而使用@Value注解修飾的字段不需要提供set方法
四、SpringBoot與整合其他技術(shù)
4.1 SpringBoot整合Mybatis
4.1.1 添加Mybatis的起步依賴
<!--mybatis起步依賴-->
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.1.1</version>
</dependency>
4.1.2 添加數(shù)據(jù)庫(kù)驅(qū)動(dòng)坐標(biāo)
<!-- MySQL連接驅(qū)動(dòng) -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId>
</dependency>
4.1.3 添加數(shù)據(jù)庫(kù)連接信息
在application.properties中添加數(shù)據(jù)量的連接信息
#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
4.1.4 創(chuàng)建user表
在test數(shù)據(jù)庫(kù)中創(chuàng)建user表
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(50) DEFAULT NULL,`password` varchar(50) DEFAULT NULL,`name` varchar(50) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '張三');
INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');
4.1.5 創(chuàng)建實(shí)體Bean
public class User {// 主鍵private Long id;// 用戶名private String username;// 密碼private String password;// 姓名private String name;//此處省略getter和setter方法 .. ..}
4.1.6 編寫Mapper
@Mapper
public interface UserMapper {public List<User> queryUserList();
}
注意:@Mapper標(biāo)記該類是一個(gè)mybatis的mapper接口,可以被spring boot自動(dòng)掃描到spring上下文中
4.1.7 配置Mapper映射文件
在src\main\resources\mapper路徑下加入U(xiǎn)serMapper.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.itheima.mapper.UserMapper"><select id="queryUserList" resultType="user">select * from user</select>
</mapper>
4.1.8 在application.properties中添加mybatis的信息
#spring集成Mybatis環(huán)境
#pojo別名掃描包
mybatis.type-aliases-package=com.itheima.domain
#加載Mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
4.1.9 編寫測(cè)試Controller
@Controller
public class MapperController {@Autowiredprivate UserMapper userMapper;@RequestMapping("/queryUser")@ResponseBodypublic List<User> queryUser(){List<User> users = userMapper.queryUserList();return users;}}
4.2 SpringBoot整合Junit
4.2.1 添加Junit的起步依賴
<!--測(cè)試的起步依賴-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope>
</dependency>
4.2.2 編寫測(cè)試類
package com.zhangcc.test;import com.zhangcc.MySpringBootApplication;
import com.zhangcc.domain.User;
import com.zhangcc.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class MapperTest {@Autowiredprivate UserMapper userMapper;@Testpublic void test() {List<User> users = userMapper.queryUserList();System.out.println(users);}}
其中,
SpringRunner繼承自SpringJUnit4ClassRunner,使用哪一個(gè)Spring提供的測(cè)試測(cè)試引擎都可以
public final class SpringRunner extends SpringJUnit4ClassRunner
@SpringBootTest的屬性指定的是引導(dǎo)類的字節(jié)碼對(duì)象
4.2.3 控制臺(tái)打印信息
4.3 SpringBoot整合Spring Data JPA
4.3.1 添加Spring Data JPA的起步依賴
<!-- springBoot JPA的起步依賴 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
4.3.2 添加數(shù)據(jù)庫(kù)驅(qū)動(dòng)依賴
<!-- MySQL連接驅(qū)動(dòng) -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId>
</dependency>
4.3.3 在application.properties中配置數(shù)據(jù)庫(kù)和jpa的相關(guān)屬性
#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
4.3.4 創(chuàng)建實(shí)體配置實(shí)體
@Entity
public class User {// 主鍵@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;// 用戶名private String username;// 密碼private String password;// 姓名private String name;//此處省略setter和getter方法... ...
}
4.3.5 編寫UserRepository
public interface UserRepository extends JpaRepository<User,Long>{public List<User> findAll();
}
4.3.6 編寫測(cè)試類
@RunWith(SpringRunner.class)
@SpringBootTest(classes=MySpringBootApplication.class)
public class JpaTest {@Autowiredprivate UserRepository userRepository;@Testpublic void test(){List<User> users = userRepository.findAll();System.out.println(users);}}
4.3.7 控制臺(tái)打印信息
注意:如果是jdk9,執(zhí)行報(bào)錯(cuò)如下:
原因:jdk缺少相應(yīng)的jar
解決方案:手動(dòng)導(dǎo)入對(duì)應(yīng)的maven坐標(biāo),如下:
<!--jdk9需要導(dǎo)入如下坐標(biāo)-->
<dependency><groupId>javax.xml.bind</groupId><artifactId>jaxb-api</artifactId><version>2.3.0</version>
</dependency>
4.4 SpringBoot整合Redis
4.4.1 添加redis的起步依賴
<!-- 配置使用redis啟動(dòng)器 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
4.4.2 配置redis的連接信息
#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
4.4.3 注入RedisTemplate測(cè)試redis操作
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class RedisTest {@Autowiredprivate UserRepository userRepository;@Autowiredprivate RedisTemplate<String, String> redisTemplate;@Testpublic void test() throws JsonProcessingException {//從redis緩存中獲得指定的數(shù)據(jù)String userListData = redisTemplate.boundValueOps("user.findAll").get();//如果redis中沒有數(shù)據(jù)的話if(null==userListData){//查詢數(shù)據(jù)庫(kù)獲得數(shù)據(jù)List<User> all = userRepository.findAll();//轉(zhuǎn)換成json格式字符串ObjectMapper om = new ObjectMapper();userListData = om.writeValueAsString(all);//將數(shù)據(jù)存儲(chǔ)到redis中,下次在查詢直接從redis中獲得數(shù)據(jù),不用在查詢數(shù)據(jù)庫(kù)redisTemplate.boundValueOps("user.findAll").set(userListData);System.out.println("===============從數(shù)據(jù)庫(kù)獲得數(shù)據(jù)===============");}else{System.out.println("===============從redis緩存中獲得數(shù)據(jù)===============");}System.out.println(userListData);}}