码云私人令牌70e0a7b76ff3e5f2d8871729ac48ee28
a.该阶段如何学习 b.SpringBoot核心思想:约定大于配置
基于Spring,默认配置了许多框架的使用,用于敏捷,迅速开发基于Spring框架的应用程序
SpringBoot的优点:
- 为所有的Spring开发者更快的入门
- 开箱即用,提供各种默认配置,简化项目配置
- 内嵌式简化web项目
- 没有多余代码,和xml配置
将service变成小模块
一种架构风格,建成一系类小服务组合,可以通过http进行互通
缺点:给部署和运维带来难度
单体应用架构:易于开发和测试,修改维护困难
微服务架构:将独立的元素动态组合,节省资源,每个功能元素的服务都可以替换,升级
d.第一个SpringBoot程序 1.创建项目原理:官方集成了****https://start.spring.io/这个spring的官网
使用idea创建,选择spring initalizr,依赖用spring web,Java8使用
2.创建包需要Apllication的同级目录下
细节:
- web层简化到只要写一个接口
- 打包形成的jar包就是一个个服务,前后端分离,数据由后端写的 服务jar包接口提供,不需要依赖idea,本身就是一个可以执行的程序
- 创建时包名可以只要前面部分
controller
@Controller
@RequestMapping("/hello")
public class HelloController {
@GetMapping("/hello")
@ResponseBody
public String hello(){
return "hello";
}
}
application.properties
#更改项目的端口号 server.port=8081e.自动配置原理
pom.xml
- spring-boot-dependencies : 核心依赖在在父工程中
- 引入依赖时,不需要指定版本号,因为有这些版本仓库
启动器
org.springframework.boot spring-boot-starter
springboot的启动场景
比如spring-boot-starter-web,会自动导入web的所有依赖
SpringBoot会将所有功能场景,变成一个个启动器,使用功能时,只要找到对应的启动器
主程序
//@SpringBootApplication标注这是一个SpringBoot项目
@SpringBootApplication
public class HellowWordApplication {
//将springboot启动
public static void main(String[] args) {
SpringApplication.run(HellowWordApplication.class, args);
}
}
注解 ctrl+左键 进入注解
SpringBootConfiguration :springboot配置 Configuration spring配置 Component spring的一个组件
结论:SpringBoot的所有自动配置都是在启动时扫描并加载:spring.factories所有的自动配置类都在这里面,会以类名的方式将需要的组件添加到容器中,但是不一定会生效,要判断条件是否成立,只有导入了对应的starter ,有了对应的启动器,自动装配才会生效,才会配置成功,这样以前需要手动配置的东西,就自动配置好了;
f.主启动run方法不只是运行了一个run方法,开启了一个服务
1.首先判断是一个普通项目还是web项目
2.推断并设置main方法的定义类,找到运行的主类
3.存在监听器,获取上下文,处理bean
g.yaml语法讲解原理:自定义才能解决更多的功能,自动配置只能写个helloword
springboot使用全局的配置文件,配置文件是固定的
application.properties
语法:key=value
server.port=8081
applicaion.yaml
key:空格value
server poet: 8081
语法结构
#普通的key=value
name: qingjiang
#对象
student:
name: qingian
age: 3
#行内写法
student1: {name: qinjiang,age: 15}
#数组
pets:
-cat
-dog
-pig
pets1: [cat,dog,pig]
#可以注入到配置类中,值可以写到yaml中,Java类中可以为空
细节:
对空格的要求很高,空格表示层级关系
student:
name:
age:表示student和name两个类,age.name age下的属性
h.给属性赋值的几种方式
原理:
1.new
2.Spring方式@Value
类
@Component
public class Dog {
@Value("旺财")
private String name;
@Value("3")
private Integer age;
测试
class SpringBoot02ConfigApplicationTests {
@Autowired
private Dog dog;
@Test
void contextLoads() {
System.out.println(dog );
}
}
3.yaml直接注入
类注入,只要在spring中就能自动注入
为了确保能够扫描到类,需要加入@Component
person类
@ConfigurationProperties(prefix = "person")
application.yaml
person:
name: qiang
age: 20
happy: true
birth: 2001/9/06
maps: {k1: v1,k2: v2}
lists:
-code
-music
-boy
dog:
name: 旺财
age: 3
扩展:
yaml中可以使用EI表达式
name: ${person.hello:hello}_旺财
i.JSR303验证
@Validated //数据校验
public class Person {
@Email()
松散绑定
yaml中可以用first-name,可以与类中firstName对应,因为-后面是默认大写的
j.多环境配置及配置文件位置优先级1234,默认的是优先级最低的
多环境切换
同一个项目中有不同的环境
application.yml
server:
port: 8081
spring:
profiles:
active: dev
---
server:
port: 8082
spring:
profiles: dev
---
server:
port: 8083
spring:
profiles: test
k.自动配置原理再理解
SpringBoot程序中,在spring.factories有大量的自动配置类xxxconfiguration,当我们要写某个功能时,先判断功能有没有在自动配置类中,有的话然后看所需要的组件有没有在自动配置类,存在组件的话就不用手动配置,不存在需要手动添加组件,需要从properties自动配置类中获取某些属性,然后在yml配置文件中给属性赋值就行了
l.web开发探究 m.静态资源导入探究创建应用前先写一个 controller,确保tomcat等一些配置能用
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello,world";
}
}
看源码,需要下载
找类,双击shirt
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
addResourceHandler(registry, "/webjars/**", "classpath:/meta-INF/resources/webjars/");
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
registration.addResourceLocations(resource);
}
});
}
静态资源可以放在
- resources目录下的public static(默认)resources和根目录/* 访问地址 localhost:8080/hello.js*
- webjars 访问地址localhost:8080/webjars/
- 优先级 resources>static>public
首页放在static resouces public都可
图标定制 版本更新,源码也会改变
o.thymeleaf模板引擎模板引擎thymeleaf:其实jsp(后台查询数据发给jsp,jsp可以实现数据的显示,和交互)也是一个模板引擎,由于springboot使用war包和内嵌tomcat,不支持jsp,只能用纯静态页面,所以SpringBoot用thymeleaf代替jsp
thymeleaf官网:Thymeleaf 教程 - Thymeleaf | Docs4dev
模板引擎工作原理:按照data中的数据把hello${user}表达式解析,把数据填充到指定位置,然后把内容写出去
原理:首先需要模板引擎thymeleaf支持数据显示,并且在templates中的所有页面都只能通过Controller跳转,不能通过RestController
1.maven导入thymeleaf依赖2.templates中写html页面org.springframework.boot spring-boot-starter-thymeleaf
test.html
测试
使用thymeleaf需要导入命名约束,方便提示
3.controller中设置接收请求,跳转页面
@GetMapping("/test")
public String test(Model model){
model.addAttribute("msg","helloSpringboot");
//通过前缀访问
return "test";
}
4、访问即可
p.thymeleaf语法
model.addAttribute("msg", " springboot");
model.addAttribute("users", Arrays.asList("qiang","zhi"));
官方文档Thymeleaf 教程 - Thymeleaf | Docs4dev
q.mvc配置原理狂神说SpringBoot12:MVC自动配置原理 - 遇见狂神说 - 博客园 (cnblogs.com)
自定义视图解析器:自己写一个视图解析器,注册到Bean中,就会自动装配
//扩展mvc配置视图解析器
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//viewResolver 实现了视图解析器的类,我们就把它当做视图解析器,配置Bean,放在Spring中
@Bean
public ViewResolver myViewResolve(){
return new MyViewResolver();
}
//自定义一个自己的视图解析器
public static class MyViewResolver implements ViewResolver{
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
在SpringBoot中有非常多xxxconfiguration帮助我们自动配置,只要我们看见了,就要注意了
员工管理系统 a.准备工作细节:date导包需要导入util中
区分:类型Employee 对象employee 员工daoEmployeeDao
1.导入静态资源
细节:
- 静态资源下载网站bootstrap模板 bootstrap模板免费下载 (chinaz.com)
- css img js放在static下,html放在templates下
2.创建实体类
添加lombook依赖,为实体类的自动生成做准备
@Data
@AllArgsConstructor
@NoArgsConstructor
org.projectlombok
lombok
员工表
Employee
@Data
@NoArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
private Integer gender; //性别 0 女, 1,男
private Department department;
private Date birth;
public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
this.birth = new Date();
}
}
细节:
- date data的区别,date导包要是util下的
- 可以查看目录结构
- lombook依赖自动生成
部门表
Department
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
private Integer id;
private String departmentName;
}
3.dao层创建临时数据库
DepartmentDao
/部门dao
//被spring托管
@Repository
public class DepartmentDao {
//模拟数据库中的数据,初始化去加载
private static Map departments = null;//创建一个库
static {
departments = new HashMap();//创建一个部门表
departments.put(101, new Department(101, "教学部"));
departments.put(102, new Department(102, "市场部"));
departments.put(103, new Department(103, "教研部"));
departments.put(104, new Department(104, "运营部"));
departments.put(105, new Department(105, "后勤部"));
}
//获得所有部门的信息
public Collection getDepartments(){
return departments.values();
}
//通过id得到部门
public Department getDepartmentById(Integer id){
return departments.get(id);
}
}
EmployeeDao
//员工dao
@Repository //被string托管
public class EmployeeDao{
//模拟数据库中的数据
private static Map employees= null;
//员工所属的部门
@Autowired
private DepartmentDao departmentDao;
static {
employees = new HashMap(); //创建一个部门表
employees.put(1001,new Employee( 1001,"AA","1622840727@qq.com",1,new Department(101,"教学部")));
employees.put(1002,new Employee( 1002,"BB","2622840727@qq.com",0,new Department(102,"市场部")));
employees.put(1003,new Employee( 1003,"CC","4622840727@qq.com",1,new Department(103,"教研部")));
employees.put(1004,new Employee( 1004,"DD","5628440727@qq.com",0,new Department(104,"运营部")));
employees.put(1005,new Employee( 1005,"FF","6022840727@qq.com",1,new Department(105,"后勤部")));
}
//主键初始化
private static Integer initId = 1006;
//增加一个员工
public void save(Employee employee){
//主键自增
if(employee.getId() == null){
employee.setId(initId++);
}
//通过编号取部门,部门关联外键
employee.setDepartment(departmentDao.getDepartmentById(employee.getDepartment().getId()));
//往employees中放employee,默认信息
employees.put(employee.getId(),employee);
}
//查询全部员工信息
public Collection getAll(){
return employees.values();
}
//通过id查询员工
public Employee getEmployeeById(Integer id){
return employees.get(id);
}
//删除员工
public void delete(Integer id){
employees.remove(id);
}
}
细节:
- **外表部门注入,EmployeeDao和DepartmentDao需要@**Repository 被spring托管,,并且还要引入@Autowired
- employees的用法
- alt全选书写
原理:扩展mvc,添加视图控制
1.扩展mvc,添加视图控制
MyMvcConfig.java
//扩展mvc
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//添加视图控制
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
}
}
2.修改html的url路径,使用thymeleaf接管,@{}
细节:
- “/"代表项目的根目录,即resouces下,static是静态目录不需要写
- 没改后端,只改前端,可以build就行,没改代码同样只要build
- 模板thymeleaf存在缓存,可以通过application,yaml配置文职关闭缓存浏览器清除缓存
#关掉模板引擎的缓存 spring.thymeleaf.cache=falsec.页面国际化
需求:实现按钮的中英文的切换
1.修改idea中的文件编码,全部改为UTF-8
2.resouces文件下创建国际化的配置文件
- 1.创建国际化配置文件
- 2.资源包下进行赋值
3.识别国际化配置文件
原理:查看源码MessageSourceAutoConfiguration
application
#绑定识别国际化配置文件 spring.messages.basename=i18n.login
4.使用thymeleaf实现html下的输出 #{},就可以实现中文,即默认语言
细节:
标签不同输出文本不同
th:text="#{login.tip}
[[#{login.remember}]]
th:placeholder="#{login.password}
5.实现中英文的切换
原理:扩展MVC实现组件,并注入到Bean中,根据获取链接的参数zh_CN和en_US不同,spring自动配置时,就会实现中英文的切换
源码分析:官网找到MessageCodesResolver,在WebMvcAutoConfiguration查找localeResolver,然后调到AcceptHeaderLocalResolver分析可知需要实现LocaleResolver就行
AcceptHeaderLocalResolver
WebMvcAutoConfiguration
-
index.html中英文按钮的链接
中文 English
细节:
- 符号‘ ’
- thymeleaf中参数赋值可以用()代替jsp中的?username=xxx
- 扩展MVC实现国际化的组件,由源码分析可知只要实现LocaleResolver
原理:获取参数
public class MyLocaleResolver implements LocaleResolver {
//解析请求
@Override
public Locale resolveLocale(HttpServletRequest request) {
//获取请求中的语言参数
String language = request.getParameter("l");
//如果没有就使用默认的
Locale locale = Locale.getDefault();
//如果请求的链接携带了国际化的参数
if(!StringUtils.isEmpty(language)){
//zh_CN
String[] split = language.split("_");
//国家,地区
locale = new Locale(split[0], split[1]);
}
return locale;
}
@Override
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
}
}
bug分析判断有没有进去方法,可以写输出语句,输出language
//获取请求中的语言参数
String language = request.getParameter("l");
System.out.println("debug=="+language);
**3.**组件注入Spring容器中@Bean,就能实现自动配置
MyMvcConfig
//注入Bean使自定义国际化组件生效,实现自动配置
@Bean
public LocaleResolver localeResolver(){
return new MyLocaleResolver();
}
总结
- 如果浏览器是中文就是中文,如果是英文就是英文,实现页面的语言,我们就需要国际化额配置文件,spring会自动使用默认的配置login.properties
- 如果要实现国际化中英文按钮的转换,我们还需要配置组件,并注入SpringBoot容器Bean中,实现点击不同的按钮获取获取不同的参数,spring就会自动配置,就可以完成中英文的切换
需求:点击登录,跳转到页面
1.改变index.html中表单中action的地址,controller实现跳转页面
index.html
//增加name属性 //修改action地址



