SpringBoot框架中有两个非常重要的策略:开箱即用和约定优于配置。
Spring Boot特点:
(1)可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs;
(2)内嵌Tomcat或Jetty等Servlet容器;
(3)提供自动配置的“starter”项目对象模型(POMS)以简化Maven配置;
(4)尽可能自动配置Spring容器;
(5)提供准备好的特性,如指标、健康检查和外部化配置;
(6)绝对没有代码生成,不需要XML配置。
创建maven工程导入起步依赖
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.0.1.RELEASEversion>
parent>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
dependencies>
package com.xmx;
/**
* 要通过SpringBoot提供的引导类起步SpringBoot才可以进行访问
*/
@SpringBootApplication
public class MySpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MySpringBootApplication.class);
}
}
浏览器访问:http://localhost:8080,出现以下结果:
package com.xmx.controller;
/**
* @Author Xumx
* @Date 2021/3/29 19:57
* @Version 1.0
*/
@Controller
public class QuickController {
@RequestMapping("/quick")
@ResponseBody
public String quick(){
return "hello springboot";
}
}
重新运行SpringBoot引导类,浏览器访问:http://localhost:8080/quick,出现以下结果:
在开发中反复修改类、页面等资源,每次修改后都是需要重新启动才生效,这样每次启动都很麻烦,浪费了大
量的时间,我们可以在修改代码后不重启就能生效,在 pom.xml 中添加如下配置就可以实现这样的功能,我们称
之为热部署。
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
dependency>
导入依赖后还需进行以下设置
首先打开setting找到Compiler勾选Build project automatically
再同时按下Ctrl+Shift+Alt+/,出现下面的选项,选择Registry
选择Registry,则出现下面配置信息,找到compiler.automake.allow.when.app.running勾选它,到此热部署配置成功。
SpringBoot是基于约定的,所以很多配置都有默认值,但如果想使用自己的配置替换默认配置的话,就可以使用application.properties或者application.yml(application.yaml)进行配置。
SpringBoot默认会从Resources目录下加载application.properties或application.yml(application.yaml)文件。
YML文件格式是YAML (YAML Aint Markup Language)编写的文件格式,YAML是一种直观的能够被电脑识别的的数据数据序列化格式,并且容易被人类阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,比如: C/C++, Ruby, Python, Java, Perl, C#, PHP等。YML文件是以数据为核心的,比传统的xml方式更加简洁。
YML文件的扩展名可以使用.yml或者.yaml。
语法: key: value
name: haohao
语法:
key:
key1: value1
key2: value2
或者:
key: {key1: value1,key2: value2}
person:
name: haohao
age: 31
addr: beijing
#或者
person: {name: haohao,age: 31,addr: beijing}
同上
语法:
key:
#注意:value1与之间的 - 之间存在一个空格
city:
- beijing
- tianjin
- shanghai
- chongqing
#或者
city: [beijing,tianjin,shanghai,chongqing]
#集合中的元素是对象形式
student:
- name: zhangsan
age: 18
score: 100
- name: lisi
age: 28
score: 88
- name: wangwu
age: 38
score: 90
application.yml配置如下:
person:
name: zhangsan
age: 18
实体Bean代码如下:
@Controller
public class QuickStartController {
@Value("${person.name}")
private String name;
@Value("${person.age}")
private Integer age;
@RequestMapping("/quick")
@ResponseBody
public String quick(){
return "springboot 访问成功! name="+name+",age="+age;
}
}
application.yml配置如下:
person:
name: zhangsan
age: 18
实体Bean代码如下:
@Controller
@ConfigurationProperties(prefix = "person")
public class QuickStartController {
private String name;
private Integer age;
@RequestMapping("/quick")
@ResponseBody
public String quick(){
return "springboot 访问成功! name="+name+",age="+age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
}
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
在springboot数据库中创建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', '李四');
在application.properties中添加数据量的连接信息
#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
package com.xmx.springboot_mybatis.domain;
/**
* @Author Xumx
* @Date 2021/4/1 21:47
* @Version 1.0
*/
public class User {
private Integer id;
private String username;
private String password;
private String name;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.xmx.springboot_mybatis.mapper;
/**
* @Author Xumx
* @Date 2021/4/1 21:51
* @Version 1.0
*/
@Mapper
public interface UserMapper {
public List<User> queryUserList();
}
在src\main\resources\mapper路径下加入UserMapper.xml配置文件
<mapper namespace="com.xmx.springboot_mybatis.mapper.UserMapper">
<select id="queryUserList" resultType="com.xmx.springboot_mybatis.domain.User">
select * from user
select>
mapper>
#spring集成Mybatis环境
#pojo别名扫描包
mybatis.type-aliases-package=com.itheima.domain
#加载Mybatis映射文件
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
package com.xmx.springboot_mybatis.controller;
/**
* @Author Xumx
* @Date 2021/4/1 21:59
* @Version 1.0
*/
@Controller
public class MybatisController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/query")
@ResponseBody
public List<User> queryUserList(){
List<User> users = userMapper.queryUserList();
return users;
}
}
<!--测试的起步依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
package com.xmx.springboot_mybatis;
import com.xmx.springboot_mybatis.domain.User;
import com.xmx.springboot_mybatis.mapper.UserMapper;
import org.junit.jupiter.api.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;
/**
* @Author Xumx
* @Date 2021/4/1 22:24
* @Version 1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootMybatisApplication.class)
public class MybatisTest {
@Autowired
private UserMapper userMapper;
@Test
public void test(){
List<User> users = userMapper.queryUserList();
System.out.println(users);
}
}
<!-- springBoot JPA的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
#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
package com.xmx.domain;
/**
* @Author Xumx
* @Date 2021/4/1 22:42
* @Version 1.0
*/
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String name;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
'}';
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.xmx.repository;
import com.xmx.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
/**
* @Author Xumx
* @Date 2021/4/1 22:45
* @Version 1.0
*/
public interface UserRepository extends JpaRepository<User,Long> {
public List<User> findAll();
}
package com.xmx;
/**
* @Author Xumx
* @Date 2021/4/1 22:48
* @Version 1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class JpaTest {
@Autowired
private UserRepository userRepository;
@Test
public void test(){
List<User> all = userRepository.findAll();
System.out.println(all);
}
}
<!-- 配置使用redis启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379
package com.xmx;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xmx.domain.User;
import com.xmx.repository.UserRepository;
import org.apache.catalina.LifecycleState;
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.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
/**
* @Author Xumx
* @Date 2021/4/2 10:07
* @Version 1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootJpaApplication.class)
public class RedisTest {
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Autowired
private UserRepository userRepository;
@Test
public void test() throws JsonProcessingException {
//1.从redis中获得数据 数据形式json字符串
String userListJson = redisTemplate.boundValueOps("user.findAll").get();
//2.判断redis中是否存在数据
if (null==userListJson){
//3.不存在数据 从数据库查询
List<User> all = userRepository.findAll();
//4.将查询出的数据存储到redis缓存中
//先将list集合转换成json格式的字符串 使用jackson进行转换
ObjectMapper objectMapper = new ObjectMapper();
userListJson = objectMapper.writeValueAsString(all);
redisTemplate.boundValueOps("user.findAll").set(userListJson);
System.out.println("=======从数据库中获得user的数据=======");
}else {
System.out.println("=======从redis缓存中获得user的数据=======");
}
//4.将数据在控制台打印
System.out.println(userListJson);
}
}
上述所有代码已上传至码云:springboot