一、SpringBoot是什么?
就是一个javaweb的开发框架,和SpringMVC类似,对比其他javaweb框架的好处,官方说是简化开发,约定大于配置, you can "just run",能迅速的开发web应用,几行代码开发一个http接口。
约定大于配置的核心思想,默认帮我们进行了很多设置,多数 Spring Boot 应用只需要很少的 Spring 配置。同时它集成了大量常用的第三方库配置(例如 Redis、MongoDB、Jpa、RabbitMQ、Quartz 等等),Spring Boot 应用中这些第三方库几乎可以零配置的开箱即用。
简单来说就是SpringBoot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架 。
Spring Boot 出生名门,从一开始就站在一个比较高的起点,又经过这几年的发展,生态足够完善,Spring Boot 已经当之无愧成为 Java 领域最热门的技术。
二、创建一个SpringBoot项目
(1)、官方创建
1、打开spring官网进入spingboot模块 链接:Spring BootLevel up your Java code and explore what Spring can do for you.https://spring.io/projects/spring-boot#overview
2、点击 Spring Initializr
3、创建项目
创建压缩包
随后解压便创建成功
(2)、idea创建
new project
一样的创建项目,添加依赖
三、启动并建包
运行Application类,就表示启动了这个springboot项目
建包要在Application这个类的同级目录下建立,否则扫描不到
创建一个controller
package com.xyh.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("hello")
public String test1(){
return "hello,boot";
}
}
运行 locahost://8080/hello 输出 hello,boot
打jar包运行项目
双击package进行jar包打包
随后在target中就出现了一个jar包
在cmd中找到本项目的target文件夹中运行此jar包
运行locahost://8080/hello 依然输出输出 hello,boot
四、 主程序Application
package com.xyh.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//标注这个类是一个springboot启动类
@SpringBootApplication
public class HelloBootApplication {
public static void main(String[] args) {
//将springboot应用启动
SpringApplication.run(HelloBootApplication.class, args);
}
}
@SpringBootApplication注解解析:启动类下的所有资源被导入
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
//springboot配置
@SpringBootConfiguration
//@Configuration:spring配置类
//@Component:是一个spring组件
//自动配置
@EnableAutoConfiguration
//@AutoConfigurationPackage:自动配置包
//@Import({AutoConfigurationImportSelector.class}):自动配置导入选择
五、application.yaml
SpringBoot使用一个全局的配置文件 , 配置文件名称是固定的
- application.properties
- 语法结构 :key=value
- application.yml/yaml
- 语法结构 :key:空格 value
配置文件注入值
新建两个类
@Component
public class Dog {
private String name;
private Integer age;
public Dog(String name, Integer age) {
this.name = name;
this.age = age;
}
public Dog() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Component
/*
@ConfigurationProperties作用:
将配置文件中配置的每一个属性的值,映射到这个组件中;
告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
参数 prefix = “person” : 将配置文件中的person下面的所有属性一一对应
*/
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> list;
private Dog dog;
public Person(){
}
public Person(String name, Integer age, Boolean happy, Date birth, Map<String, Object> maps, List<Object> list, Dog dog) {
this.name = name;
this.age = age;
this.happy = happy;
this.birth = birth;
this.maps = maps;
this.list = list;
this.dog = dog;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Boolean getHappy() {
return happy;
}
public void setHappy(Boolean happy) {
this.happy = happy;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Map<String, Object> getMaps() {
return maps;
}
public void setMaps(Map<String, Object> maps) {
this.maps = maps;
}
public List<Object> getList() {
return list;
}
public void setList(List<Object> list) {
this.list = list;
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", happy=" + happy +
", birth=" + birth +
", maps=" + maps +
", list=" + list +
", dog=" + dog +
'}';
}
}
在application.yaml中就可以给类的属性赋值
person:
name: xss
age: 3
happy: true
birth: 2020/05/05
maps: {k1:v1,k2:v2}
list:
- code
- music
- girl
dog:
name: 旺财
age: 3
在test中运行
@SpringBootTest
class HelloBootApplicationTests {
@Autowired
private Person person;
@Test
void contextLoads() {
System.out.println(person);
}
}
就可输出
Person{name='xss', age=3, happy=true, birth=Tue May 05 00:00:00 CST 2020, maps={k1v1=, k2v2=}, list=[code, music, girl], dog=Dog{name='旺财', age=3}}
yaml还可以赋值随机数以及引用值
person:
name: xss
//随机数
age: ${random.int}
happy: true
birth: 2020/05/05
maps: {k1: v1,k2: v2}
hello: 666
list:
- code
- music
- girl
dog:
//引用person.hello的值,此处存在,则为666_旺财 不存在则为hello_旺财
name: ${person.hello:hello}_旺财
age: 3
JSR303校验
@Validated //数据校验
public class Person {
//message表示为错误的提示语
@Email(message = "错了宝")
private String name;
}
常见参数
@NotNull(message="名字不能为空")
private String userName;
@Max(value=120,message="年龄最大不能查过120")
private int age;
@Email(message="邮箱格式错误")
private String email;
空检查
@Null 验证对象是否为null
@NotNull 验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank 检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty 检查约束元素是否为NULL或者是EMPTY.
Booelan检查
@AssertTrue 验证 Boolean 对象是否为 true
@AssertFalse 验证 Boolean 对象是否为 false
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内
@Length(min=, max=) string is between min and max included.
日期检查
@Past 验证 Date 和 Calendar 对象是否在当前时间之前
@Future 验证 Date 和 Calendar 对象是否在当前时间之后
@Pattern 验证 String 对象是否符合正则表达式的规则
.......等等
除此以外,我们还可以自定义一些数据校验规则
application.yaml可以放的位置以及执行顺序
优先级1:项目路径下的config文件夹配置文件
优先级2:项目路径下配置文件
优先级3:资源路径下的config文件夹配置文件
优先级4:资源路径下配置文件
配置多个环境
1、properties
写3个配置文件
分别写三个不同的端口号
server.port=8080/8081/8082
因为默认走的时是application.properties,所以,默认端口号为8080,如果想要改变端口号
则可以在application.properties中写上要使用的配置文件名
# springboot的多环境配置,可以选择激活哪一个配置文件(写后缀名即可)
spring.profiles.active=dev
表示使用application-test.properties配置文件,端口号则为8081
2、yaml
还是上个例子,在yaml中表示为
server:
prot: 8080
spring:
profiles:
active: dev
---
server:
prot: 8081
spring:
profiles: dev
---
server:
prot: 8082
spring:
profiles: test
三、静态资源问题
springboot的静态资源可以存放如下位置
并且优先级为resources>static(默认)>public
四、首页
取名一定要为index.html,与静态资源相同,也可以放在public,resources,static文件夹中,优先级也与静态资源一致
五、国际化编写
新建一个文件夹名称为i18n,在里面建立2个properties,名称分别为login.properties,login_zh_CN.properties,会发现两者合并到一起了
点击添加一个新的properties
输入en_Us,就会自动识别
在login_zh_CN 或 login_en_Us中点击 Resource Bundle 变为可视化界面 ,就可以创建新的组件
如图
之后在配置文件中配置
spring.messages.basename=i18n.login
这样 配置的login才可以生效
注意!!!:一定要在utf-8的编码格式下才能运行,否则乱码
在html页面上使用
<div th:text="#{login.Username}"></div> //注意使用的是#{}
展示为 用户名
当需要切换中英文时,就需要自己手动写一个地区解析类来替换掉springboot为我们写好的类
package com.xyh.Config;
import org.springframework.web.servlet.LocaleResolver;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class MyLocalResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求参数
String language = request.getParameter("l");
Locale locale = Locale.getDefault(); //没有就是用默认的
if(!StringUtils.isEmpty(language)){
String [] split = language.split("_");
locale = new Locale(split[0],split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
随后将此类配置到容器中
package com.xyh.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyConfig implements WebMvcConfigurer {
//自定义的国际化组件
@Bean
public LocaleResolver localeResolver(){
return new MyLocalResolver();
}
}
在html中使用th:href来通过自定义的国际化组件来解析为哪国的语言
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div th:text="#{login.Username}"></div>
<div th:text="#{login.tip}"></div>
<div th:text="#{login.Password}"></div>
<br>
//注意,thymeleaf的href传参使用的是()
<a style="color: black;text-decoration: none" th:href="@{/index(l='zh_CN')}">中文</a>
<a style="color: black;text-decoration: none" th:href="@{/index(l='en_Us')}">英文</a>
</body>
</html>
六、springboot自动配置原理
springboot是通过main方法下的SpringApplication.run方法启动的,启动的时候他会调用refshContext方法,先刷新容器,然后根据解析注解或者解析配置文件的形式祖册bean,而它是通过启动类的SpringBootApplication注解进行开始解析的,他会根据EnableAutoConfiguration开启自动化配置,里面有个核心方法ImportSelect选择性的导入,根据loadFanctoryNames根据classpash路径以MATA-INF/spring.factorces下面以什么什么EnableAutoConfiguration开头的key去加载里面所有对应的自动化配置,他并不是把这一百二十多个自动化配置全部导入,在他每个自动化配置里面都有条件判断注解,先判断是否引入相互的jar包,再判断容器是否有bean再进行注入到bean容器。