Spring Boot学习(一)

目录

一、Spring Boot简介

二、SpringBoot学习

1.SpringBoot入门

1.通过网站搭建项目 

2.通过IDEA脚手架搭建项目

3.Spring项目结构

4.通过Maven搭建项目

5.编写Java代码

2.SpringBoot原理分析

1.起步依赖

2.springboot自动配置

3.核心注解

3.YAML文件

1.yml配置集合数据

2.读取yml配置的数据

3.yaml占位符的作用

4.yaml文件的优先级

5.yaml文件bootstrap配置文件

4.Springboot注册Web组件

1.SpringBoot注册Servlet组件

2.Springboot注册Filter组件

3.Springboot注册Listener组件

5.SpringBoot访问静态资源

6.SpringBoot整合JSP


一、Spring Boot简介

SpringBootSpring的缺点进行改善和优化,基于约定大于配置的思想,简化了Spring的开发,所谓简化是指简化了Spring中大量的配置文件和繁琐的依赖引入。所以SpringBoot是一个服务于框架的框架,它不是对Spring功能的增强,而是提供了一种快速使用 Spring框架的。

Spring Boot核心特点:

1.自动配置、默认配置(项目自动提供最优配置,同时可以修改默认值满足特定要求

2.起步依赖:starter一站式(依赖基于功能,将所有坐标打包一起,并完成版本适配

3.创建独立Spring应用程序

4.嵌入Tomcat,无需WAR

5.监控能力强

6.较少需要xml配置

Spring Boot版本介绍:

CURRENT;最新GA版本

GA:发布版本,面向大众的稳定版本,发布后不会再更改

SNAPSHOT;快照版本,随时可能修改

二、SpringBoot学习

1.SpringBoot入门

1.通过网站搭建项目 

  

访问start.spring.io

生成springBoot项目

 下载之后解压导入IDEA即可。

SpringBoot打包成一个JAR包,因为springboot直接嵌入了tmcat等web容器,所以在需要使用SpringBoot做web开发的时候不需要部署War文件,只需打包成Jar包即可。

2.通过IDEA脚手架搭建项目

 使用Default或者选择国内阿里云的镜像网站,但是镜像网站版本比较滞后。

 选择版本以及需要的依赖

3.Spring项目结构

 

 Demo Application.java:启动类,启动main方法即可启动springboot项目。

application.properties: 配置类,文件内容会覆盖默认配置。

SpringBoot项目必须继承spring-boot-starter-parent,即所有的SpringBoot项目都是spring-boot-starter-parent的子项目。spring-boot-starter-parent中定义了常用配置、依赖、插件等信息,供SpringBoot项目继承使用。

4.通过Maven搭建项目

 创建普通maven项目,然后pom.xml中添加父工程、起步依赖、插件

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.3</version>
            </plugin>

 编写启动类:

package com.yygs.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

 配置文件:

application.properties

5.编写Java代码

 springboot会自动扫描启动类同级类、包内或者同级包下的子包内类的注解。

在启动类同级包下创建MyController类:

package com.yygs.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
        System.out.println("hello,springboot!");
        return "hello springboot!";
    }
}

2.SpringBoot原理分析

1.起步依赖

2.springboot自动配置

进入配置类上的注解:

 注解里的注解引入类,类里有方法加载各种配置属性 

3.核心注解

@SpringBootApplication

标注是SpringBoot的启动类。 此注解等同于

@SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan

@EnableAutoConfiguration

SpringBoot自动配置注解。 等同于

@AutoConfigurationPackage + @Import(AutoConfigurationImportSelector.class)

@AutoConfigurationPackage

自动扫描包的注解,它会自动扫描主类所在包下所有加了注解的类

@Controller@Service等),以及配置类 (@Configuration)。

@Import({AutoConfigurationImportSelector.class})

该注解会导入 AutoConfifigurationImportSelector 类对象,该对象会从 META-INF/spring.factories 文件中读取配置类的名称列表

@ComponentScan

该注解会扫描项目,自动装配一些项目启动需要的Bean

3.YAML文件

 Springboot支持proerties和yaml这两种文件。SpringBoot默认会从resources目录下加载application.properties或application.yml文件。其中,application.properties文件是键值对类型的文件。

yaml或yml文件:

大小写敏感

使用缩进代表层级关系

相同的部分只出现一次

比如使用properties文件配置tomcat端口:

server.port=8888

而使用YAML文件配置tomcat端口:

server:

        port: 8888

 除了覆盖默认配置,我们还可以在YAML文件中配置其他信息以便我们在项目中使用。配置简单数据的方式如下:语法: 值 (冒号后面要有一个空格) 

 示例:

student1:

        sex: female

        age: 10

        address: guangzhou

对象:

        属性名1: 属性值

        属性名2: 属性值

# 或者

对象: {属性名1: 属性值,属性名2: 属性值}

 属性值前面的空格数多少都可以,但是要保证同级别的空格数一样。

1.yml配置集合数据

 - 后面需要有个空格

集合:

        - 1

        - 2

# 或者

集合: [1,2]

# 城市

city1:

        - beijing

        - tianjin

        - shanghai

city2: [beijing,tianjin,shanghai,chongqing]

# 集合中的元素是对象

students:

        - name: baizhan

          age: 18

          score: 100

        - name: shangxuetang

          age: 28

          score: 88

        - name: chengxuyuan

          age: 38

          score: 90

2.读取yml配置的数据

我们可以通过@Value注解将配置文件中的值映射到一个Spring管理的Bean的字段上,用法如下:

@Controller
public class YmlController1 {
    @Value("${name}")
    private String name;

    @Value("${student1.age}")
    private int age;

    @Value("${city1[0]}")
    private String city1;

    @Value("${students[0].score}")
    private double score1;

    @RequestMapping("/yml1")
    @ResponseBody
    public String yml1(){
        System.out.println(name);
    }
}

但是只能获取到简单属性,不能获将集合、对象等属性映射到bean中。

通过 @ConfigurationProperties(prefifix="对象") 可以将配置文件中的配置自动与实体进行映射,这样可以将yml文件中配置的对象属性直接映射到Bean当中。(属性名要一致

3.yaml占位符的作用

YAML文件中可以使用 ${} 占位符,它有两个作用:

1:

server:
  port: 8888
myconfig:
  myport: ${server.port}
@Controller
public class YmlController3 {
    @Value("${myconfig.myport}")
    private int port;

}

2:

使用框架提供的方法

SpringBoot框架提供了一些生成随机数的方法可以在yml文件中使用:

${random.value} :生成类似uuid的随机数,没有"-"连接

${random.uuid} :生成一个uuid,有短杠连接

${random.int} :随机取整型范围内的一个值

${random.int(10)}:随机生成一个10以内的数

${random.int(100,200)}:随机生成一个100-200 范围以内的数

${random.long}:随机取长整型范围内的一个值

${random.long(100,200)}:随机生成长整型100-200范围内的一个值

4.yaml文件的优先级

配置文件有如下存放位置:

项目根目录下

项目根目录下的/config子目录中

项目的resources目录中

项目的resources下的/config子目录中

优先级为:

项目根目录下的config内 > 项目根目录 > 项目的resources下的config目录内 > 项目的resource目录

同级内:properties > yaml

5.yaml文件bootstrap配置文件

SpringBoot中有两种容器对象,分别是bootstrapapplication,bootstrap是应用程序的父容器,bootstrap加载优先于applicaton。bootstrap配置文件主要对bootstrap容器进行配置,application配置文件是对applicaton容器进行配置。bootstrap配置文件也同样支持propertiesyml两种格式,主要用于从外部引入Spring应用程序的配置。

bootstrap配置文件特征

1.boostrap由父ApplicationContext加载,比applicaton优先加载。

2.boostrap里面的属性不能被覆盖。

bootstrapapplication的应用场景:

application配置文件主要用于SpringBoot项目的自动化配置。

bootstrap配置文件有以下几个应用场景:

使用Spring Cloud Config配置中心时,需要在bootstrap配置文件中添加连接到配置中心的配置属性来加载外部配置中心的配置信息。2

一些固定的不能被覆盖的属性。

一些加密/解密的场景。

4.Springboot注册Web组件

1.SpringBoot注册Servlet组件

方法一:

1.创建springboot项目

2.创建Servlet类并加上@WebServlet注解:

@WebServlet("/first")
public class FirstServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("...");
    }
}

3.在启动类上加@ServletComponentScan注解

@SpringBootApplication
@ServletComponentScan //Springboot启动时扫描注册注解标注的web组件
public class Springbootdemo2Application {

    public static void main(String[] args) {
        SpringApplication.run(Springbootdemo2Application.class, args);
    }

}

方法二:

1.创建springboot项目

2.创建Servlet类:

public class SecondeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("...");
    }
}

3.编写配置类:

在启动类同级上创建ServletConfig类并加上@Configuration注解:

@Configuration
public class ServletConfig {

    // ServletRegistrationBean可以注册Servlett组件,将其放入IOC容器,即可注册
    @Bean
    public ServletRegistrationBean getServletRegisterationBean(){
        // 注册组件
        ServletRegistrationBean bean = new ServletRegistrationBean(new SecondeServlet());
        // 添加Servlet访问路径
        bean.addUrlMappings("/second");
        return bean;
    }
}

2.Springboot注册Filter组件

方式一:

在启动类同级创建filter\FirstFilter类:

并加上@WebFilter注解

@WebFilter(urlPatterns = "/first")
public class FirstFilter implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("进入Filter");
        chain.doFilter(request,response);
        System.out.println("离开Filter");
    }

    @Override
    public void destroy() {

    }
}

在启动类上添加@ServletComponentScan注解

@SpringBootApplication
@ServletComponentScan //Springboot启动时扫描注册注解标注的web组件
public class Springbootdemo2Application {

    public static void main(String[] args) {
        SpringApplication.run(Springbootdemo2Application.class, args);
    }

}

方式二:

创建Filter类:

public class SecondFiter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("进入Filter");
        chain.doFilter(request,response);
        System.out.println("离开Filter");
    }

    @Override
    public void destroy() {

    }
}

在启动类同级上创建FilterConfig类并加上@Configuration注解:

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean getfilterRegistrationBean(){
        // 注册Filter组件
        FilterRegistrationBean bean = new FilterRegistrationBean(new SecondFiter());
        // 添加过滤路径
        bean.addUrlPatterns("/second");
        return bean;
    }
}

3.Springboot注册Listener组件

方式一:

在启动类同级创建listener\firstListener类:

并加上@WebListener注解

@WebListener
public class FirstListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("First Listener Init");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        
    }
}

在启动类上添加@ServletComponentScan注解

@SpringBootApplication
@ServletComponentScan //Springboot启动时扫描注册注解标注的web组件
public class Springbootdemo2Application {

    public static void main(String[] args) {
        SpringApplication.run(Springbootdemo2Application.class, args);
    }

}

方式二:

创建Listener类:

public class SecondeListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("First Listener Init");
    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }
}

在启动类同级上创建ListenerConfig类并加上@Configuration注解:

@Configuration
public class ListenerConfig {
    @Bean
    public ServletListenerRegistrationBean getServletListenerRegistrationBean(){
        ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean(new SecondeListener());
        return bean;
    }
}

5.SpringBoot访问静态资源

 resources目录下:

SpringBoot项目中没有WebApp目录,只有src目录。在src/main/resources 下面有 static templates 两个文件夹。SpringBoot默认在static 目录中存放静态资源,可以先创建包,包内再放资源,而 templates 中放动态页

templates目录

SpringBoot中不推荐使用JSP作为动态页面,而是默认使用Thymeleaf编写动态页面。templates目录是存放Thymeleaf页面的。

其他目录:

除了 /resources/static 目录,SpringBoot还会扫描以下位置的静态资源:

/resources/METAINF/resources/

/resources/resources/

/resources/public/

 我们还可以在配置文件自定义静态资源位置,不过需要在application.properties文件内进行配置。但是配置文件内的配置的路径资源会把没定义的资源覆盖,那么需要的话就要在文件内也添加没定义的资源。

6.SpringBoot整合JSP

SpringBoot中不推荐使用JSP作为动态页面,我们要想使用JSP编写动态页面,需要手动添加webapp目录。同时,由于SpringBoot自带tomcat无法解析JSP,需要在pom文件添加JSP引擎:

1.添加依赖:

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <version>10.0.17</version>
        </dependency>

2.在main目录下创建webapp包

3.将webapp变成web

Project Structure -》 Moudles -》Web -》 添加web -》选择刚刚创建的webapp包 -》OK

4. 在webapp目录下创建WEB-INF,在里面编写jsp

 5.在application.properties里配置视图解析器

spring:

mvc:

  view:

    prefix: /WEB-INF/jsp/

    suffix: .jsp

6.编写controller

@Controller
public class PageController {
    @GetMapping("/{page}")
    public String showPage(@PathVariable String page){
        return page;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值