Springboot的相關的配置和技術
1、YML語法的格式問題
1.1、簡單的鍵值對問題
K: V語法規則就是這樣
注意:如果value是字符串的話 這裏是不需要寫""
1、如果寫了""結果是什麼?
eg: key2: “this is xiaobobo \n And you?”
那麼他輸出的內容是: this is xiaobobo 換行 And you?
2、如果你寫成了’ '那麼結果又是什麼?
key2:‘this is xiaobobo \n And you?’
如果是單引號 他會將 後面的值 當成一個普通的字符來處理
key2:‘this is xiaobobo \n And you?’
1.2、如果傳遞了對象、map集合(鍵值對)
friends:
name: tiedan
age: 18
friends1: {name: tiedan,age: 18}
1.3、數組的寫法
habbits:
- boy
- girl
- other
habbits1: [boy,girl,other]
1.4、測試圖
2、配置文件模式選擇的問題
說明一個問題:咋們項目的開發一般有三種模式
dev:開發模式
test:測試模式
prod:生產模式
問題產生:就是我們在做開發的時候 有可能根據不同的開發模式 來選擇不同的配置文件
例子:dev 模式 我們就需要選擇開發模式的配置文件
2.1、appication.properties中的文件
#激活哪一種環境(說白了 激活哪一種環境 就會自動去選擇哪種環境下的配置文件
# dev test prod
spring.profiles.active=prod
2.2、就是目錄結構
2.3、application.yml格式
2.3.1、第一種模式(application.yml)
1、配置主的application.yml文件
spring:
profiles:
active: prod
2、目錄的結構
2.3.2、yml中的第二種寫法
spring:
profiles:
active: prod
---
spring:
profiles: dev
server:
port: 9876
---
spring:
profiles: test
server:
port: 6789
---
spring:
profiles: prod
server:
port: 8787
3、SpringBoot整合SSM框架
3.1、首先是導包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--使用Druid這個連接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
3.2、編寫application.properties文件
#給java實體取別名
mybatis.type-aliases-package=com.qf.shopping.pojo
#告訴他mapper.xml文件所在的位置
mybatis.mapper-locations=classpath:mapper/*.xml
#連接數據庫的配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///1904
spring.datasource.username=root
spring.datasource.password=root
#設置連接池的類型
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#給應用取名字
spring.application.name=shopping-ssm
3.3、編寫配置文件(AppConfig)
@SpringBootConfiguration //表示是一個配置文件
@ComponentScan(basePackages = {"com.qf.shopping"}) //這個就是原來spring配置中的掃描
@MapperScan(basePackages = {"com.qf.shopping.mapper"}) //這個是掃描 mapper接口所在的位置
public class AppConfig {
}
3.4、編寫mapper
public interface UserMapper {
/**
* 通過id找到用戶
* @param id
* @return
*/
User findUserById(int id);
}
3.5、編寫mapper.xml文件
<!--要注意的第二點-->
<mapper namespace="com.qf.shopping.mapper.UserMapper">
<!--通過id找到用戶-->
<select id="findUserById" parameterType="int" resultType="user">
select * from t_user where id=#{value}
</select>
</mapper>
3.6、編寫Service的接口
public interface IUserService {
/**
* 通過id找用戶
* @param id
* @return
*/
User findUserById(int id)throws Exception;
}
3.7、編寫Service的實現
@Service
@Transactional
public class UserService implements IUserService {
@Autowired
private UserMapper userMapper;
@Override
public User findUserById(int id) {
return userMapper.findUserById(id);
}
}
3.8、編寫控制器
@RestController
public class UserController {
@Autowired
private IUserService userService;
/**
* 通過id找用用戶
* @param id
* @return
*/
@RequestMapping("findUserById")
public UserResult findUserById(int id){
UserResult result = new UserResult();
result.setState(0); //默認是失敗的
try {
User user = userService.findUserById(id);
result.setState(1);
result.setUser(user);
} catch (Exception e) {
//說明請求是失敗的
result.setErrorMsg("通過id獲取用戶數據失敗:"+e.getMessage());
}
return result;
}
}
3.9、編寫返回結果集的基類
@Data
@AllArgsConstructor
@NoArgsConstructor
public class BaseResult {
//每一次給前端返回的狀態
private int state; // 0:請求失敗 1:請求成功
private String errorMsg; //錯誤的原因是什麼
}
3.10、編寫User的返回結果集
@Data
@AllArgsConstructor
@NoArgsConstructor
public class UserResult extends BaseResult{
private User user;
private List<User> users;
}
4、SpringBoot整合dbunit
4.1、測試的原理
4.2、首先就是基類的編寫
public class AbstractDbunitTestCase {
private DatabaseConnection conn; //這個不是真真的數據庫的連接的 封裝
private File tempFile; //這個就是臨時文件
private IDataSet dataSetTestData;
public AbstractDbunitTestCase(String testDataName) throws DatabaseUnitException {
dataSetTestData=new FlatXmlDataSet(new FlatXmlProducer(new InputSource(AbstractDbunitTestCase.class.getClassLoader().getResourceAsStream(testDataName))));
}
/**
* 這個方法的作用就是初始化上面的DatabaseConnection
* @param conn1
*/
public void setConn(Connection conn1) throws DatabaseUnitException {
conn=new DatabaseConnection(conn1);
}
/**
* 備份多個包
* @param tabNames
*/
public void backManyTable(String... tabNames) throws DataSetException, IOException {
QueryDataSet dataSet = new QueryDataSet(conn);
//第二步:設置要備份的這個表
for (String tabName:tabNames) {
dataSet.addTable(tabName);
}
//接下來就是備份了
tempFile=File.createTempFile("back",".xml");
//備份
FlatXmlDataSet.write(dataSet,new FileOutputStream(tempFile));
}
/**
* 備份一張表
* @param tabName
*/
public void backOneTable(String tabName) throws IOException, DataSetException {
backManyTable(tabName);
}
/**
* 插入測試數據
*/
public void insertTestData() throws DatabaseUnitException, SQLException {
DatabaseOperation.CLEAN_INSERT.execute(conn,dataSetTestData);
}
/**
* 還原表的數據
*/
public void resumeTable() throws DatabaseUnitException, SQLException, FileNotFoundException {
IDataSet dataSet=new FlatXmlDataSet(new FlatXmlProducer(new InputSource(new FileInputStream(tempFile))));
DatabaseOperation.CLEAN_INSERT.execute(conn,dataSet);
}
}
4.3、測試的編寫
@RunWith(SpringRunner.class) //下面的註解是SpringBoot對dbunit的支持
@SpringBootTest(classes = Application.class) //和原來測試的區別(導入了SpringBoot的運行環境)
public class TestUserMapper extends AbstractDbunitTestCase {
private User exUser; //期望返回的數據
@Autowired
private DataSource dataSource;
@Autowired
private UserMapper userMapper;
public TestUserMapper() throws DatabaseUnitException {
super("testdata.xml");
}
@Before //前置通知
public void init() throws SQLException, DatabaseUnitException, IOException {
exUser=new User(10,"小波波1","111");
setConn(dataSource.getConnection());
backOneTable("t_user");
insertTestData();
}
@Test
public void testFindUserById(){
//調用方法
User acUser = userMapper.findUserById(10);
//斷言(就是看請求回來的數據 和預期的數據是否一致)
Assert.assertEquals(exUser.getId(),acUser.getId());
Assert.assertEquals(exUser.getUserName(),acUser.getUserName());
Assert.assertEquals(exUser.getPassword(),acUser.getPassword());
}
/**
* 還原數據
*/
@After
public void destory() throws FileNotFoundException, DatabaseUnitException, SQLException {
resumeTable();
}
}
4.5、導包
<!--導入SpringBoot對dbunit測試的支持-->
<dependency>
<groupId>com.github.springtestdbunit</groupId>
<artifactId>spring-test-dbunit</artifactId>
<version>1.3.0</version>
<scope>test</scope>
</dependency>
<!--導入dbunit自己的包-->
<dependency>
<groupId>org.dbunit</groupId>
<artifactId>dbunit</artifactId>
<version>2.5.3</version>
</dependency>
5、SpringBoot下使用thymeleaf
5.1、Thymeleaf是什麼
Thymeleaf是一個模板引擎
Thymeleaf簡單的跟你說 就是做開發的時候 用來顯示前端頁面以及數據的這樣一個框架
Thymeleaf這個框架 就有點類似於 前面學習的jsp 功能主要就是頁面的顯示和數據的綁定
5.2、Thymeleaf能幹什麼
簡單的說、支持很多頁面模板(HTML)、以及可以實現以前jsp在頁面上實現的所有功能
5.3、Thymeleaf的使用
5.3.1、導包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
5.3.2、配置
# 配置模板引擎的這個前綴
spring.thymeleaf.prefix=classpath:/templates/
#配置模板引擎的訪問後綴
spring.thymeleaf.suffix=.html
#配置模板引擎的這個模板的類型
spring.thymeleaf.mode=HTML5
#設置模板的內容編碼
spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type=text/html
#配置模板的緩存
spring.thymeleaf.cache=false
5.3.3、編寫controller
/**
* 跳轉到bobo這個頁面去
* @return
*/
@RequestMapping("toBobo")
public String toBobo(Model model){
model.addAttribute("userName","小王子");
//放入一個對象進去
User user = new User(1, "鐵蛋", "110");
model.addAttribute("user",user);
return "bobo";
}
5.3.4、編寫模板頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
this is bobo page And you? <br>
<hr/>
<!--獲取單個值-->
用戶名是:<span th:text="${userName}"></span>
<span>xxxxx</span><br>
<!--獲取對象的值-->
獲取到的對象的值是:<br>
用戶名: <span th:text="${user.userName}"></span><br>
密碼:<span th:text="${user.password}"></span><br>
</body>
</html>