0
点赞
收藏
分享

微信扫一扫

手把手初认Springboot2


Springboot

Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者。

Springboot是Spring中的一个成员,可以简化Spring,SpringMVC的核心是IOC容器

使用Springboot开发效率高。

Springboot特点

  1. 独立运行的 Spring 项目

Spring Boot 可以以 jar 包的形式独立运行,Spring Boot 项目只需通过命令“ java–jar xx.jar” 即可运行。

可以创建独立的Spring应用程序,并且基于其Maven或Gradle插件,可以创建可执行的JARs和WARs;

  1. 内嵌 Servlet 容器

Spring Boot 使用嵌入式的 Servlet 容器(例如 Tomcat、Jetty 或者 Undertow 等),应用无需打成 WAR 包 。

  1. 提供 starter 简化 Maven 配置

Spring Boot 提供了一系列的“starter”项目对象模型(POMS)来简化 Maven 配置。

  1. 提供了大量的自动配置

Spring Boot 提供了大量的默认自动配置,来简化项目的开发,开发人员也通过配置文件修改默认配置。

尽可能自动配置Spring容器

  1. 自带应用监控

Spring Boot 可以对正在运行的项目提供监控。

  1. 无代码生成和 xml 配置

Springboot特性

    遵循习惯优于配置的原则。使用springboot我们只需要很少的配置,大多数使用默认配置即可

    内嵌servlet容器,降低了对环境的要求,可用命令直接执行项目

    项目快速搭建。springboot尽可能自动配置spring以及第三方库,帮助开发者快速搭建spring框架,可无需配置的自动整合第三方框架

    提供各种starter简化Maven配置。springboot提供了一系列的starter用来简化maven依赖。如:常用的spring-boot-starter-web、spring-boot-starter-tomcat等

    独立运行spring项目。springboot可以以jar包的形式进行独立运行,使用java -jar xx.jar 就可以成功运行项目,无需部署war文件

    可以完全不使用xml配置,只需要自动配置和Java config

    应用监控(SpringBootActuator)

XML与JavaConfig

Spring使用XML作为容器配置文件,在3.0后加入了JavaConfig,使用java类做配置文件使用。

JavaConfig

JavaConfig:是Spring提供使用java类配置容器(代替XML配置。配置Spring IOC容器的纯Java方法。

JavaConfig类可以创建java对象,把java对象放入spring容器中(注入)。

可以使用面向对象方式,一个配置类可以继承配置类,可以重写方法。

避免了繁琐的XML配置

注解:@Configuration 、 @Bean

@Configuration:表示这个类作为配置文件使用

@Bean:声明对象,把对象注入到IOC容器中。

XML配置文件配置与JavaConfig配置注入IOC容器

pojo类

public class Student {

    private String name;

    private int age;

    private String sex;
       //get+set+toString
}

分别使用XML配置与JavaConfig配置方式将Student对象注入IOC容器

XML配置文件配置

springConfig.xml

<bean id="student" class="com.qgs.pojo.Student">

    <property name="name" value="张三"></property>

    <property name="age" value="18"></property>

    <property name="sex" value="男"></property>

</bean>

测试类

@Test

public void test01(){

    ApplicationContext applicationContext =new ClassPathXmlApplicationContext("springConfig.xml");

    Student student = applicationContext.getBean("student", Student.class);

    System.out.println(student.toString());

}

JavaConfig配置@Configuration

/**

 * @Configuration注解:表示该类作为配置文件使用。用来配置IOC容器。

 * 使用@Configuration注解后SpringConfig类,代替springConfig.xml

 */

@Configuration

public class SpringConfig {

    /**

     * 创建方法其返回值为对象,加入@Bean注解后,对象就注入到IOC容器中

     */

//未使用@Bean注解来指定Bean的名字则默认为方法名

    @Bean

    public Student createStudent(){

        Student st1 =new Student();

        st1.setName("李四");

        st1.setAge(20);

        st1.setSex("男");

        return st1;

    }

}

测试类

@Test

public void test02(){

    ApplicationContext aC =new AnnotationConfigApplicationContext(SpringConfig.class);

    Student createStudent = aC.getBean("createStudent", Student.class);

    System.out.println(createStudent.toString());

}

手把手初认Springboot2_配置文件

使用@bean注解指定名称

@Bean(name ="Student001")

 

手把手初认Springboot2_java_02

引入@ImportResource

@ImportResource作用:导入其他xml配置文件,等同于

等同于在xml中使用import

<import resource="classpath:xxxx.xml"/>

@ImportResource的使用

@ImportResource(value ="classpath:applicationContext.xml")

 

手把手初认Springboot2_spring_03

手把手初认Springboot2_java_04

@PropertyResource注解

手把手初认Springboot2_配置文件_05

@PropertyResource注解是读取properties属性配置文件,类似于在xml配置文件中的

<!--引入外部文件-->

<context:property-placeholder location="classpath:jdbc.properties"/>

@PropertyResource注解的使用

在resources目录下创建properties文件,使用key=value格式提供数据

手把手初认Springboot2_java_06

创建类

@Component("jdbc")

public class Jdbc {

  @Value("${jdbc.driver}")

  private String  driver;

  @Value("${jdbc.url}")

  private String  url;

  @Value("${jdbc.user}")

  private String  user;

  @Value("${jdbc.password}")

  private String  password;

  //get + set + toString

}

SpringConfig配置

@ComponentScan({"com.qgs.pojo"})

@PropertySource(value = "classpath:jdbc.properties")

 

手把手初认Springboot2_配置文件_07

测试类

@Test

public void test02(){

    ApplicationContext aC =new AnnotationConfigApplicationContext(SpringConfig.class);

    Jdbc jdbc = aC.getBean("jdbc", Jdbc.class);

    System.out.println(jdbc.toString());

}

创建SpringBoot项目的方式

使用Spring提供的初始化器,向导创建springboot项目

DIEA使用国外地址:

https://start.spring.io

DIEA使用国内地址

https://start.springboot.io

手把手初认Springboot2_java_08

手把手初认Springboot2_spring_09

 

手把手初认Springboot2_java_10

浏览器构建项目

手把手初认Springboot2_配置文件_11

手把手初认Springboot2_spring_12

手把手初认Springboot2_spring boot_13

IDEA导入包

手把手初认Springboot2_配置文件_14

使用Maven构造SpringBoot项目

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <parent>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-parent</artifactId>

        <version>2.7.10</version>

        <relativePath/> <!-- lookup parent from repository -->

    </parent>

    <groupId>org.example</groupId>

    <artifactId>springboot004</artifactId>

    <version>1.0-SNAPSHOT</version>
    <properties>

        <maven.compiler.source>8</maven.compiler.source>

        <maven.compiler.target>8</maven.compiler.target>

        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    </properties>
    <dependencies>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

        <dependency>

            <groupId>org.mybatis.spring.boot</groupId>

            <artifactId>mybatis-spring-boot-starter</artifactId>

            <version>2.3.0</version>

        </dependency>
        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-devtools</artifactId>

            <scope>runtime</scope>

            <optional>true</optional>

        </dependency>

        <dependency>

            <groupId>com.mysql</groupId>

            <artifactId>mysql-connector-j</artifactId>

            <scope>runtime</scope>

        </dependency>

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </dependency>

    </dependencies>
    <build>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>
</project>

@SpringBootApplication注解

@SpringBootApplication注解由

@SpringBootConfiguration

@EnableAutoConfiguration

@ComponentScan

组成

手把手初认Springboot2_java_15

@SpringBootApplicatio

手把手初认Springboot2_spring boot_16

@SpringBootConfiguration

手把手初认Springboot2_spring_17

@SpringBootConfiguration注解标注的类,可以作为配置文件使用,可以声明Bean对象,注入容器中。

@EnableAutoConfiguration

手把手初认Springboot2_bc_18

@EnableAutoConfiguration注解:启动自动配置,将java对象配置好,注入到Spring容器中。列如将Mybatis的对象创建好注入Spring容器中。

@ComponentScan组件扫描器。根据注解功能创建对象,属性赋值。

Spring Boot核心配置文件

Spring Boot核心配置文件用于配置Spring Boot程序,名字以application开始

Spring Boot默认使用Properties配置文件

Properties配置文件

使用application.properties可以配置端口,web根路径等

#设置端口号
server.port=8080
#设置访问路径 contextPath
server.servlet.context-path=/boot

手把手初认Springboot2_java_19

Yml配置文件

YAML (YAML Ain’t a Markup Language)YAML不是一种标记语言,通常以.yml为后缀的文件,是一种直观的能够被电脑识别的数据序列化格式,并且容易阅读,容易和脚本语言交互的,可以被支持YAML库的不同的编程语言程序导入,一种专门用来写配置文件的语言。

YML语法

    k: v 表示键值对关系,冒号后面必须有一个空格

    使用空格的缩进表示层级关系,空格数目不重要,只要是左对齐的一列数据,都是同一个层级的

    大小写敏感

    缩进时不允许使用Tab键,只允许使用空格。

    java中对于驼峰命名法,可用原名或使用-代替驼峰,如java中的lastName属性,在yml中使用lastName或 last-name都可正确映射。

    yml中注释前面要加#

 

手把手初认Springboot2_spring_20

Properties配置文件与Yml配置文件对比

 

手把手初认Springboot2_配置文件_21

Springboot创建多环境配文件

Whitelabel Error Page问题

产生原因:目录结构错误

方法返回值问题

返回的不是模板,而是字符串时,Controller类需要添加 注解 @RestController,或方法添加@ResponseBody

 

手把手初认Springboot2_bc_22

解决办法1

 

手把手初认Springboot2_java_23

解决办法2

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

多环境配置

Spring Boot提供了多环境配置

每个环境有不同的ConfigInfo,Port,Context,Jdbc_url,username,password等

使用多环境配置文件,可以方便的切换不同的配置。

开发环境、生产环境、测试环境。

名称规则:application-环境名称.properties(yml)

开发环境::application-dev. yml

生产环境: application-produce.yml

测试环境:application-test.yml

Spring Boot默认使用application.properties

手把手初认Springboot2_spring boot_24

#application.properties配置文件

##设置端口号

#server.port=8080

##设置访问路径 contextPath

#server.servlet.context-path=/boot
#使用哪个配置环境

spring.profiles.active=dev

#application.yml配置文件

#使用哪个配置环境

spring:

  profiles:

    active: dev

#开发环境配置

server:

  port: 8081

  servlet:

    context-path: /dev

#生产环境配置

server:

  port: 8083

  servlet:

    context-path: /produce

#测试环境配置

server:

  port: 8082

  servlet:

    context-path: /test

Spring Boot自定义配置

@Value注解

使用@value注解获取自定义参数

手把手初认Springboot2_spring_25

手把手初认Springboot2_bc_26

#application.properties配置文件

##设置端口号

server.port=8080

##设置访问路径 contextPath

server.servlet.context-path=/boot
#自定义key=value

t.name=qgs

t.age=3

t.address=深圳

@Value("${server.port}")

private int port;

@Value("${server.servlet.context-path}")

private String contextPath;

@Value("${t.name}")

private String name;

@Value("${t.age}")

private int age;

@Value("${t.address}")

private String address;
@RequestMapping("/hello")

@ResponseBody

public String getDateValue(){

    return port+"  "+contextPath+"  "+name+"/  "+age+"  "+address;

}

@ConfigurationProperties注解

将配置文件的数据映射为一个对象,用于自定义配置项较多的情况

pom.xml配置

<!--        处理ConfigurationProperties元数据-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-configuration-processor</artifactId>

            <optional>true</optional>

        </dependency>

手把手初认Springboot2_配置文件_27

@ConfigurationProperties(prefix = "t")

 

手把手初认Springboot2_bc_28

springmvc测试

手把手初认Springboot2_java_29

 

手把手初认Springboot2_spring boot_30

SpringBoot使用JSP

SpringBoot不推荐使用JSP,推荐使用模板技术代替JSP

pom.xml文件配置

加入依赖

<dependency>

    <groupId>org.apache.tomcat.embed</groupId>

    <artifactId>tomcat-embed-jasper</artifactId>

</dependency>

<dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>javax.servlet-api</artifactId>

</dependency>

<dependency>

    <groupId>javax.servlet.jsp</groupId>

    <artifactId>javax.servlet.jsp-api</artifactId>

    <version>2.2.1</version>

</dependency>

<dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>jstl</artifactId>

</dependency>

创建webapp目录

手把手初认Springboot2_java_31

手把手初认Springboot2_java_32

pom.xml文件配置

手把手初认Springboot2_spring_33

<!--指定jsp编译后的存放目录-->

<resources>

    <resource>

        <!--原目录-->

        <directory>src/main/webapp</directory>

        <!--指定要处理的目录和文件 **/*.*表示任意文件和子目录的任意文件-->

        <includes>

            <include>**/*.*</include>

        </includes>

        <!--指定编译后的存放目录-->

        <targetPath>META-INF/resources</targetPath>

    </resource>

</resources>

Controller

@Controller

public class JspController01 {

    @Resource

    private StudentInfo sInfo;

    @RequestMapping("/jsp")

    public String doJsp(Model model){
        //model将数据放入到request作用域

        model.addAttribute("sInfo",sInfo);  //model == request.setAttribute("sInfo",sInfo);
        return "index";

    }
}

application.properties配置视图解析器

#配置视图解析器

# / 表示在webapp目录下

spring.mvc.view.prefix=/

spring.mvc.view.suffix=.jsp

Index.jsp

<body>

<h3>姓名:${sInfo.name} 年龄:${sInfo.age} 地址:${sInfo.address}</h3>

</body>

 

手把手初认Springboot2_配置文件_34

Spring Boot 使用ApplicationContext获取容器对象

在main方法中SpringApplication.run()方法获取返回的Spring容器对象,在获取业务bean进行调用。

手把手初认Springboot2_spring boot_35

public static void main(String[] args) {

    //获取容器对象

    ConfigurableApplicationContext run = SpringApplication.run(StudentApplication.class, args);

    StudentInfo studentInfo = (StudentInfo) run.getBean("studentInfo");

    System.out.println(studentInfo.toString());

}

使用CommandLineRunner接口

在开发过程中会有在容器启动后执行一些内容。如连接数据库,读取配置文件等。SpringBoot提供了两个接口:CommandLineRunner和ApplicationRunner,来实现,这两个接口中有一个run方法。两个接口的不同之处是:CommandLineRunne中的run方法参数为String数组,而ApplicationRunner中的run方法参数为ApplicationArguments。

手把手初认Springboot2_spring boot_36

 

手把手初认Springboot2_配置文件_37

如有错误请指正,谢谢

举报

相关推荐

0 条评论