SpringBoot

SpringBoot : 微服务框架,简化spring初始搭建及开发过程,Spring技术栈的大整合,j2ee开发一站式解决方案。

微服务:架构风格,每个功能元素最终都是可独立替换和独立升级的软件单元;一个应用应该是一组小型服务,能根据http方式进行互通。

spring-boot-starter:spring-boot场景启动器;导入了web模块正常运行所依赖的组件;它将所有的功能场景都抽取出来,做成一个个的starters(启动器),只需要在项目里面引入这些starter相关场景的所有依赖都会导入进来。

主程序入口:

SpringBootConfiguration:Spring Boot的配置类;标注在某个类上,表示这是一个Spring Boot的配置类;
Configuration:配置类上来标注这个注解;
配置类 -----  配置文件;配置类也是容器中的一个组件;@Component
EnableAutoConfiguration:开启自动配置功能;
AutoConfigurationPackage:自动配置包
Spring的底层注解@Import,给容器中导入一个组件
将主配置类(@SpringBootApplication标注的类)的所在包及下面所有子包里面的所有组件扫描到Spring容器;
EnableAutoConfigurationImportSelector:导入哪些组件的选择器;
将所有需要导入的组件以全类名的方式返回;这些组件就会被添加到容器中;
SpringBoot在启动的时候从类路径下META-INF/spring.factories中获取EnableAutoConfiguration指定的值,将这些值作为自动配置类导入到容器中生效,帮我们进行自动配置工作
J2EE的整体整合解决方案和自动配置都在spring-boot-autoconfigure-1.5.9.RELEASE.jar;

 全局的配置文件,配置文件名是固定的---YAML:以数据为中心,比json、xml等更适合做配置文件;

配置文件加载位置:

 springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件
–file:./config/
–file:./
–classpath:/config/
–classpath:/
优先级由高到底,高优先级的配置会覆盖低优先级的配置;
SpringBoot会从这四个位置全部加载主配置文件;互补配置; 可以通过spring.config.location来改变默认的配置文件位置

用命令行参数的形式,启动项目的时候来指定配置文件的新位置;指定配置文件和默认加载的这些配置文件共同起作用形成互补配置;
java -jar spring-boot-config-02-0.0.1-SNAPSHOT.jar   --spring.config.location=G:/application.properties

自动配置原理:

  1.   SpringBoot启动的时候加载主配置类,开启了自动配置功能   @EnableAutoConfiguration
  2. 将 类路径下  META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中,启动指定类的ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;并把HttpEncodingProperties加入到ioc容器中
  3. 根据当前不同的条件判断,决定这个配置类是否生效;一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;
  4. 所有在配置文件中能配置的属性都是在xxxxProperties类中封装着;配置文件能配置什么就可以参照某个功能对应的这个属性类

日志

SpringBoot选用     SLF4j    和    logback

如何让系统中所有的日志都统一到slf4j
​    1)、SpringBoot底层也是使用slf4j+logback的方式进行日志记录
​    2)、SpringBoot也把其他的日志都替换成了slf4j;
​    3)、中间替换包 

  4)、如果我们要引入其他框架,一定要把这个框架的默认日志依赖移除掉;Spring框架用的是commons-logging;

//记录器
     Logger logger = LoggerFactory.getLogger(getClass());
     @Test
     public void contextLoads() {
         //日志的级别;
         //由低到高   trace<debug<info<warn<error
         //可以调整输出的日志级别;日志就只会在这个级别以以后的高级别生效
         logger.trace("这是trace日志...");
         logger.debug("这是debug日志...");
         //SpringBoot默认给我们使用的是info级别的,没有指定级别的就用SpringBoot默认规定的级别;root级别
         logger.info("这是info日志...");
         logger.warn("这是warn日志...");
         logger.error("这是error日志...");
     }

模板引擎

SpringBoot推荐的Thymeleaf;语法更简单,功能更强大;

1、引入thymeleaf;

<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
        切换thymeleaf版本
<properties>
		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
		<!-- 布局功能的支持程序  thymeleaf3主程序  layout2以上版本 -->
		<!-- thymeleaf2   layout1-->
		<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
  </properties>

2、Thymeleaf使用

 只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;
使用:
    1、导入thymeleaf的名称空间  <html lang="en" xmlns:th="http://www.thymeleaf.org">

    2、使用thymeleaf语法;

3、语法规则

 1)、th:text;改变当前元素里面的文本内容;      th:任意html属性;来替换原生属性的值

 2)、表达式

Simple expressions:(表达式语法)
    Variable Expressions: ${...}:获取变量值;OGNL;
    		1)、获取对象的属性、调用方法
    		2)、使用内置的基本对象:
    			#ctx : the context object.
    			#vars: the context variables.
                #locale : the context locale.
                #request : (only in Web Contexts) the HttpServletRequest object.
                #response : (only in Web Contexts) the HttpServletResponse object.
                #session : (only in Web Contexts) the HttpSession object.
                #servletContext : (only in Web Contexts) the ServletContext object.
                ${session.foo}
            3)、内置的一些工具对象:
            #execInfo : information about the template being processed.
            #messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
            #uris : methods for escaping parts of URLs/URIs
            #conversions : methods for executing the configured conversion service (if any).
            #dates : methods for java.util.Date objects: formatting, component extraction, etc.
            #calendars : analogous to #dates , but for java.util.Calendar objects.
            #numbers : methods for formatting numeric objects.
            #strings : methods for String objects: contains, startsWith, prepending/appending, etc.
            #objects : methods for objects in general.
            #bools : methods for boolean evaluation.
            #arrays : methods for arrays.
            #lists : methods for lists.
            #sets : methods for sets.
            #maps : methods for maps.

Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
    	补充:配合 th:object="${session.user}:
   <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
    </div>
Message Expressions: #{...}:获取国际化内容
Link URL Expressions: @{...}:定义URL;
		@{/order/process(execId=${execId},execType='FAST')}
Fragment Expressions: ~{...}:片段引用表达式
		<div th:insert="~{commons :: main}">...</div>

Literals(字面量)
      Text literals: 'one text' , 'Another one!' ,…
      Number literals: 0 , 34 , 3.0 , 12.3 ,…
      Boolean literals: true , false
      Null literal: null
Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(数学运算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布尔运算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比较运算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:条件运算(三元运算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)

 扩展SpringMVC:
    编写一个配置类(@Configuration),是WebMvcConfigurerAdapter类型;不能标注@EnableWebMvc

//使用WebMvcConfigurerAdapter可以来扩展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //浏览器发送 /atguigu 请求来到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
    //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
            }
        };
        return adapter;
    }
}

 原理:
​    1)、WebMvcAutoConfiguration是SpringMVC的自动配置类
​    2)、在做其他自动配置时会导入;@Import(**EnableWebMvcConfiguration**.class)

    3)、容器中所有的WebMvcConfigurer都会一起起作用;  4)、我们的配置类也会被调用;
​    效果:SpringMVC的自动配置和扩展配置都会起作用;

全面接管SpringMVC      配置类中添加@EnableWebMvc即可

/**
 * 登陆检查,
 */
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if(user == null){
            //未登陆,返回登陆页面
            request.setAttribute("msg","没有权限请先登陆");
            request.getRequestDispatcher("/index.html").forward(request,response);
            return false;
        }else{
            //已登陆,放行请求
            return true;
        }

    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

注册拦截器
  //所有的WebMvcConfigurerAdapter组件都会一起起作用
    @Bean //将组件注册在容器
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("dashboard");
            }
            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //super.addInterceptors(registry);
                //静态资源;  *.css , *.js
                //SpringBoot已经做好了静态资源映射
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
                        .excludePathPatterns("/index.html","/","/user/login");
            }
        };
        return adapter;
    }

注册Servlet三大组件【Servlet、Filter、Listener】

 由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。
注册三大组件用以下方式

//ServletRegistrationBean
@Bean
public ServletRegistrationBean myServlet(){
    ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(),"/myServlet");
    return registrationBean;
}

//FilterRegistrationBean
@Bean
public FilterRegistrationBean myFilter(){
    FilterRegistrationBean registrationBean = new FilterRegistrationBean();
    registrationBean.setFilter(new MyFilter());
    registrationBean.setUrlPatterns(Arrays.asList("/hello","/myServlet"));
    return registrationBean;
}

//ServletListenerRegistrationBean
@Bean
public ServletListenerRegistrationBean myListener(){
    ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
    return registrationBean;
}
SpringBoot帮我们自动SpringMVC的时候,自动的注册SpringMVC的前端控制器;DIspatcherServlet;DispatcherServletAutoConfiguration中

嵌入式Servlet容器启动原理

1)、SpringBoot应用启动运行run方法

 2)、refreshContext(context);SpringBoot刷新IOC容器【创建IOC容器对象,并初始化容器,创建容器中的每一个组件】;如果是web应用创建**AnnotationConfigEmbeddedWebApplicationContext**,否则:**AnnotationConfigApplicationContext**

 3)、refresh(context);**刷新刚才创建好的ioc容器;**

4)、  onRefresh(); web的ioc容器重写了onRefresh方法

 5)、webioc容器会创建嵌入式的Servlet容器;**createEmbeddedServletContainer**();

6)、获取嵌入式的Servlet容器工厂:**
EmbeddedServletContainerFactory containerFactory = getEmbeddedServletContainerFactory();
​    从ioc容器中获取EmbeddedServletContainerFactory 组件;**TomcatEmbeddedServletContainerFactory**创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制Servlet容器的相关配置;

 7)、**使用容器工厂获取嵌入式的Servlet容器**:this.embeddedServletContainer = containerFactory      .getEmbeddedServletContainer(getSelfInitializer());

 8)、嵌入式的Servlet容器创建对象并启动Servlet容器;
**先启动嵌入式的Servlet容器,再将ioc容器中剩下没有创建出的对象获取出来;**
**==IOC容器启动创建嵌入式的Servlet容器==**

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值