1.在intellij idea中創(chuàng)建一個spring boot項(xiàng)目
步驟如下:
完成傻瓜式操作后就可以創(chuàng)建一個springboot項(xiàng)目結(jié)構(gòu)如下圖
2.創(chuàng)建一個controller
@RestController
@RequestMapping("")
public class UserController {
@RequestMapping("")
public String index(){
return "Hello World!";
}
}
項(xiàng)目結(jié)構(gòu)如下圖所示
啟動main函數(shù)控制臺出現(xiàn)如下所示說明啟動成功
瀏覽器訪問:默認(rèn)端口8080
注解解釋:@RestController注解相當(dāng)于@ResponseBody + @Controller合在一起的作用蚁趁。
3.整合Mybatis到springboot
在pom中添加以下依賴
<!--===============添加mybatis依賴================-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
application.properties中添加配置
spring.datasource.url=jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
創(chuàng)建數(shù)據(jù)表
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
瀏覽器輸入訪問接口:http://localhost:8080/query結(jié)果如圖所示
此時項(xiàng)目結(jié)構(gòu)如下
注解:
@ComponentScan
注解開啟后會掃描到項(xiàng)目中所有注解
@MapperScan
可以替代dao層接口的@mapper
注解颁糟,作用是:使用此注解可以注冊 Mybatis 接口類
4.設(shè)置靜態(tài)資源前后綴
#配置靜態(tài)資源前后綴
spring.mvc.view.prefix=/web/
spring.mvc.view.suffix=.html
設(shè)置PageController頁面接口
@Controller
@RequestMapping
public class PageController {
@RequestMapping("index")
public String index(){
return "index";
}
}
訪問接口:http://localhost:8080/index結(jié)果如下所示
此時項(xiàng)目結(jié)構(gòu)如下所示:
5.切換application.properties 為application.yml
yml和properties文件是一樣的原理,yml屬性結(jié)構(gòu)是將配置文件中的信息樹形展示出來,更便于查看衅胀,但語法要求比較嚴(yán)格腔彰。
- application.properties
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=utf8
spring.datasource.username = root
spring.datasource.password = root
#=========Mybatis 相關(guān)配置==================
#mapper文件
mybatis.mapperLocations=classpath:mapper/*.xml
#可省略寫mybatis的xml中的resultType的全路徑
mybatis.type-aliases-package=com.example.systemspringboot.entity
#配置靜態(tài)資源前后綴
spring.mvc.view.prefix=/web/
spring.mvc.view.suffix=.html
- application.yml
spring:
datasource:
password: root
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=utf8
username: root
#配置靜態(tài) 資源前后綴
mvc:
view:
prefix: /web/
suffix: .html
#=========Mybatis 相關(guān)配置==================
#1.mapper文件
#2.可省略寫mybatis的xml中的resultType的全路徑
mybatis:
mapperLocations: classpath:mapper/*.xml
type-aliases-package: com.example.systemspringboot.entity
-
推薦一個將application.properties 轉(zhuǎn)換為application.yml的網(wǎng)站:地址
所屬文集:SpringBoot學(xué)習(xí)
項(xiàng)目地址:GitHub