SpringBoot入门及初步理解

SpringBoot

特征

  • 创建独立的Spring应用程序
  • 直接嵌入Tomcat,Jetty或Undertow(无需部署WAR文件)
  • 提供自以为是的“入门”依赖项,以简化您的构建配置
  • 尽可能自动配置Spring和3rd Party库
  • 提供可用于生产的功能,例如指标,运行状况检查和外部化配置
  • 完全没有代码生成,也不需要XML配置
  • 简化开发,约定大于配置

自动配置

pom.xml

spring -boot-dependencies:核心依赖在父工程中!

我们在写或者引入一些Springboot一来的时候,不需要指定版本,就因为有这些版本仓库

启动器

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

启动器:说白了就是Springboot的启动场景

spring-boot-starter-web帮助我们自动导入web环境所有的依赖

springboot会将所有的功能场景,都变成一个个的启动器

我们要使用什么功能,就只需要找到对应的启动器就可以啦

主程序

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//@SpringBootApplication 标注这个类是一个springboot的应用:启动类下的所有资源
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        //将Springboot应用启动
        SpringApplication.run(DemoApplication.class, args);
    }

}

在这里插入图片描述

注解

@SpringBootConfiguration: springboot的配置

​ @Configuration: spring配置类

​ @Component: 这说明也是一个spring的组件

@EnableAutoConfiguration: 自动导入包配置

​ @AutoConfigurationPackage: 自动配置包

​ @Import(AutoConfigurationPackages.Registrar.class): 自动注册表

​ @Import(AutoConfigurationImportSelector.class): 自动导入包的核心

//获取所有配置

List configurations= getCandidateConfigurations(annotationMetadata,attributes);

获取候选的配置

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
    List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
    Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
    return configurations;
}

结论:springboot所有的自动配置都在启动类中被扫描并加载:spring.factories所有的自动配置类都在这里,但是不一定生效要判断条件是否成立,只要导入了对应的start,就有对应的启动器了,有了启动器,我们的装配就会生效,然后配置成功!

1.springboot在启动的时候,从类路径下/META-INF/spring.factories获取指定的值

2.讲这些自动配置的类导入容器,自动配置就会生效,帮我们进行配置!

3.以前我们需要自动配置的东西,现在springboot帮我们作了!

4.整合javaEE,解决方案和自动配置的东西都在spring-boot-autoconfigure-2.2.0.RELEASE.jar这个包

5.他会把所有需要导入的组件,以类名的方式返回,这些组件就会被添加到容器;

6.容器中也会存在非常多的XXXautoconfiguration的文件,就是这些类给容器中导入了这个场景需要的所有组件,并自动配置,@Configuration,JavaConfig!

7.有了自动配置类,免去了我们手动编写配置文件的工作!

主启动类

在main方法中,有一个服务SpringApplicatiom.run

//参数一:应用入口的类  参数二:命令行参数
SpringApplication.run(DemoApplication.class, args);

该方法主要分为两部分,一部分是SpringApplication的实例化,二是run方法的执行;

SpringApplication做以下四件事:

1.推断应用的类型是普通的项目或是Web项目

2.查找并加载所有可用初始化器,设置到initializers属性中

3.找出所有的应用程序监听器,设置到listeners属性中

4.推断并设置main方法的定义类,找到运行的主类

JavaConfig @Configuration//配置类 @Bean//组件

SpringBoot配置文件及自动配置

配置文件

SpringBoot是一个全局配置文件,配置文件名称是固定的

application.properties 语法结构:key=value

application.yml 语法结构: key:空格value

作用:修改SpringBoot自动配置的默认值,springboot在底层都已经自动配置完成。

YAML

以前的配置文件大多是xml来配置,比如:

xml配置:

<server>
    <port>8080rt>
</server>    

yaml配置:

server:
    prot: 8080

基本语法:

application.yaml

#k=v
#对空格的要求高
#普通的key-value
#可以注入到配置类中
name: wj

#对象
student:
  name: wj
  age: 23
  
#行内写法
student: {name: wj,age: 23}

#数组
pets:
 - cat
 - dog
 
pets: [cat,dog] 

application.porperties

#只能保存键值对
name=wj

student.name=wj
student.age=23

yaml可以直接给实体类赋值

JSR303校验

@Email //被注释的元素必须为电子邮箱格式

@Length //备注是的字符串的大小必须在指定的范围内

@NotEmpty//被注释的字符必须非空

@Range//被注释的元素必须在合适的范围内

@NotNull(message=“名字不能为空”)

@Max(value=120 message=“最大不能超过120”)

@Null验证对象是否为空

@NotBlank 检查字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前面空格

Boolean检查

@AssertTrue 验证Boolean对象是否为True

@AssertFalse
在这里插入图片描述
在这个jar包下的该路径可以查看源码

日期检查

@Past 验证Date和Calender 对象是否在当前对象之前

@Future 验证Date和Calender 对象是否在当前对象之后

@Pattern验证String对象是否符合验证正则表达式的规则

配置环境位置

1.file:./config/

2.file:./

3.classpath:/config/

4.classpath:/

又优先级

#springboot的多环境配置,可以选择激活哪一个配置文件

spring.profiles.active=dev

service:
	port:8081
spring:
	profiles:
     active:dev
   
-----------------
service:
	port:8082
spring:
	profiles:dev
	
-----------------
service:
	port:8083
spring:
	profiles:test

自动装配原理总结:

1.SpringBoot启动会加载大量的自动配置类

2.我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中

3.我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在其中,我们就不需要再手动配置了)

4.给容器中自动配置类添加组件时,会从properties类中获取某些属性,我们只需要在配置文件中指定这些属性的值即可

SpringBoot Web开发

WebMvcConfigurer配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。

xxxxAutoConfigurarion:自动配置类;给容器中添加组件

xxxxProperties:封装配置文件中相关属性;

debug: true//可以查看日志中组件是否执行

静态资源导入

void addResourceHandlers(ResourceHandlerRegistry var1)//添加资源处理器

在springboot,我们可以使用以下方式处理静态资源

  • webjars localhost:8080/webjars/

  • public,static,/**,resource localhost:8080/

2.优先级:

resources>static(默认)>public

首页图标

   @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext, FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
            WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(new TemplateAvailabilityProviders(applicationContext), applicationContext, this.getWelcomePage(), this.mvcProperties.getStaticPathPattern());
            welcomePageHandlerMapping.setInterceptors(this.getInterceptors(mvcConversionService, mvcResourceUrlProvider));
            welcomePageHandlerMapping.setCorsConfigurations(this.getCorsConfigurations());
            return welcomePageHandlerMapping;
        }
//欢迎页的处理映射,首页映射    

        private Resource getWelcomePage() {
            String[] var1 = this.resourceProperties.getStaticLocations();
            int var2 = var1.length;

            for(int var3 = 0; var3 < var2; ++var3) {
                String location = var1[var3];
                Resource indexHtml = this.getIndexHtml(location);
                if (indexHtml != null) {
                    return indexHtml;
                }
            }

            ServletContext servletContext = this.getServletContext();
            if (servletContext != null) {
                return this.getIndexHtml((Resource)(new ServletContextResource(servletContext, "/")));
            } else {
                return null;
            }
        }

        private Resource getIndexHtml(String location) {
            return this.getIndexHtml(this.resourceLoader.getResource(location));
        }

        private Resource getIndexHtml(Resource location) {
            try {
                Resource resource = location.createRelative("index.html");
                if (resource.exists() && resource.getURL() != null) {
                    return resource;
                }
            } catch (Exception var3) {
            }

            return null;
        }
public FormattingConversionService mvcConversionService()//mvc的转换映射
protected RequestMappingHandlerMapping createRequestMappingHandlerMapping()//处理器请求映射
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer//配置绑定初始化
 protected void extendHandlerExceptionResolvers//扩展视图解析器
  public ContentNegotiationManager mvcContentNegotiationManager//mvc的转换管理
  
 public static class FaviconConfiguration implements ResourceLoaderAware//图标自定义  
 这个需要  <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>版本在2.0以下,在2.0版本删除了

扩展:在网上找出来的想看更全的可以在下方这个链接。

https://blog.csdn.net/zhangpower1993/article/details/89016503

 /* 拦截器配置 */
void addInterceptors(InterceptorRegistry var1);
/* 视图跳转控制器 */
void addViewControllers(ViewControllerRegistry registry);
/**
     *静态资源处理
**/
void addResourceHandlers(ResourceHandlerRegistry registry);
/* 默认静态资源处理器 */
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
/**
     * 这里配置视图解析器
 **/
void configureViewResolvers(ViewResolverRegistry registry);
/* 配置内容裁决的一些选项*/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);
/** 解决跨域问题 **/
public void addCorsMappings(CorsRegistry registry) 

Thymeleaf模板引擎

pom.xml依赖

  <!--thymeleaf模板引擎-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
    </dependencies>

都是基于3.X开发

结论:只要需要使用thymeleaf,只需要导入对应的依赖就可以了!我们将html放在我们templates目录下即可

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值