第一章 SpringBoot入门

1.SpringBoot简介

1.1.简介

        Spring Boot来简化spring应用开发,约定大于配置去繁从简,just run就能创建一个独立的,产品级别的应用。
         背景:J2EE笨重开发,繁多的配置、低下开发效率、复杂的部署流程、第三方技术集成难度大。
        解决: “Spring全家桶”时代;Spring Boot → J2EE一站式解决方案;Spring Cloud → 分布式整体解决方案。

1.2.优点

        快速创建独立运行的Spring项目以及与主流框架集成 ;使用嵌入式的Servlet容器,应用无需打成war包 ;starters自动依赖与版本控制 ;大量自动配置,简化开发,也可以修改默认值;无需配置XML,无代码生成,开箱即用;准生产环境的运行时应用监控;与云计算的天然集成。

2.微服务

         微服务:架构风格(服务微化)
        一个应用应该是一个一组小型服务;可以通过HTTP的方式进行互通;单体应用:ALL IN ONE;微服务:每一个功能元素最终都是一个可独立替换和独立升级的软件单元。

3.环境准备

        JDK1.8:SpringBoot推荐JDK1.7及以上

        Maven3.x:maven3.3以上版本

        eclipse:2018、IDEA2017或者STS

        SpringBoot2.4.4RELEASE

4.maven设置

        maven设置本地仓库,在maven的conf文件中seting.xml文件的localRepository下方加上

<!-- localRepository | The path to the local repository maven will use tostore artifacts. | | Default: ${user.home}/.m2/repository <localRepository>/path/to/local/repo</localRepository> -->


<localRepository>D:\software\maven\repository</localRepository>

<!-- interactiveMode | This will determine whether maven prompts you whenit needs input. If set to false, | maven will use a sensible default value,perhaps based on some other setting, for | the parameter in question. | |Default: true <interactiveMode>true</interactiveMode> -->

        给maven的setting.xml配置文件的profiles标签中添加

<profile>
		<id>jdk-1.8</id>
		<activation>
			<activeByDefault>true</activeByDefault>
			<jdk>1.8</jdk>
		</activation>
		<properties>
			<maven.compiler.source>1.8</maven.compiler.source>
			<maven.compiler.target>1.8</maven.compiler.target>
			<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
		</properties>
 </profile>

        maven的mirrors标签添加阿里云镜像:

<mirror>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>        
 </mirror>

maven配置环境变量:
        在系统变量新建MAVEN_HOME,D:\software\apache-maven-3.6.0;
        在Path中末尾加入:%MAVEN_HOME%\bin;

5.创建SpringBoot项目

5.1.统一编码

        根据统一编码截图设置,除了Text本身设置为UTF-8编码外,属于他的几个子节点也要改,分别是:Text下的:Java Properties;Java Properties下的:Spring Properties;Text下的:JSP;以及JSP下的两个以JSP开头的两个子节点(编码可改也可不改)。

 

 

 

5.2.创建项目

        首先选中Spring perspective,在Package Explorer导航图下,右键new选择Spring start Project弹出如下对话框:

点击Next后,直接点击Finish按钮,再次点击Finish
在pom.xml文件中,加上:

<properties>
	<java.version>1.8</java.version>
	<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
</properties>
<dependencies>

</dependencies>

        右键项目,选择Maven项目,选择更新项目(update project)
        处理完成后,启动XXXXXApplication.java的main方法,看到控制台有如下报文,就说明项目创建成功,配置也成功了!

5.3.创建一个hello world的Spring Boot项目

        功能描述: 浏览器发送hello请求,服务器接受请求并处理,响应Hello World字符串;
        1、创建一个maven工程;(jar)
        2、导入Spring Boot相关依赖

    <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.1.2</version>
		<relativePath /> <!-- lookup parent from repository -->
    </parent>
	<groupId>com.school</groupId>
	<artifactId>SpringBoot01</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringBoot01</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
		<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<!-- 这是引入jQuery的webjars依赖 -->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>jquery</artifactId>
			<version>3.6.0</version>
		</dependency>
		<!-- 引入BootStrap的webjars依赖 -->
		<dependency>
			<groupId>org.webjars</groupId>
			<artifactId>bootstrap</artifactId>
			<version>5.0.0-beta3</version>
		</dependency>

		<!-- 添加Thymeleaf依赖 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

	</dependencies>

        3、编写一个主程序;启动Spring Boot应用

/**
 * @SpringBootApplication:标注主程序,说明这是一个Spring boot应用
 * @author lenovo
 *
 */
@SpringBootApplication
public class HelloWorldMainApplication {
	public static void main(String[] args) {
		
		//启动Springboot应用程序
		SpringApplication.run(HelloWorldMainApplication.class, args);
		
	}
}

        4、编写相关的Controller、Service

@Controller
public class HelloController {

	@ResponseBody
	@RequestMapping("/hello")
	public String hello(){
		return "hello world!";
	}
}

        或者使用@RestController都是一样的效果:因为@RestController包含了@ResponseBody和@Controller两个注释:

@RestController
public class HelloController {

	@RequestMapping("/hello")
	public String hello(){
		return "hello world!";
	}
	
}

        5、运行主程序测试:
        6、简化部署:在</dependencies>加上

    <build>
		<plugins>
             <!--Spring boot把程序打成一个可执行jar包的插件-->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

  6.1.把程序达成jar包

        将这个应用打成jar包,直接使用Java -jar的命令进行执行;打包:
        有一个要求,运行环境不能只是jre,要向上到jdk

         然后到maven仓库里面找jar包,E:\learn\word\SpringBootDaMai\SpringBoot02\target

6、使用Spring Start Project快速创建项目

        Eclipse:使用Spring Start Project可以快速创建一个Spring Boot项目,选择需要的模块,这是联网去创建一个Spring Boot项目;
        默认生成的SpringBoot项目:

        主程序已经生成,接下来只需要开始业务逻辑的编写

        resources文件夹中的目录结构:

                static:保存所有的静态资源;js、css、images

                templates:保存所有的模板页面;(SpringBoot默认jar包使用嵌入式的Tomcat,默认不支持JSP页面);可以使用模板引擎(freemarker、thymeleaf);

                application.properties:SpringBoot应用的配置文件,可以修改一些默认配置。

        server.port=8085 #设置springboot运行端口为8085,默认为8080

IDEA :使用Spring Initializer快速创建SpringBoot项目

7.配置文件

        springboot使用一个全局的配置文件,配置文件名是固定的;    

  • application.properties

  • application.yml

        配置文件的作用:修改SpringBoot自动配置的默认值;SpringBoot在底层都已经配置好了的。
        YAML(YAML Ain't Markup Language)需要辨证角度看这个问题
        YAML A Markup Language:yaml是一个标记语言类似
        YAML isn‘t Markup Language:yaml不是一个标记语言
        YAML:是以数据为中心,比JSON、XML文件等更适合做配置文件
YAML:配置例子,配置项目运行端口

server:
    port: 8085

XML

<server>
	<port>8085</port>
</server>

8.YAML语法

8.1.基本语法

        k: v:表示一对键值对(==强调:空格必须要有==)。以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的

server:
    port: 8085
    path: /hello

        属性和值也是大小写敏感的。

8.2.值的写法

字面量:普通的值:数字,字符串,布尔值
        k: v:字面直接来写
                字符串默认不用加上单引号或者双引号;
                "":双引号;会对特殊字符进行转义;特殊字符会作为本身想表示的意思,例如:name: "zhangsan \n lisi",输出内容为:"zhangsan 换行 lisi"
                ’‘:单引号;不会对特殊字符进行转义;特殊字符最终只是一个普通的字符串数据,例如:name: "zhangsan \n lisi",输出内容为:"zhangsan 换行 lisi"

        对象、Map、K-V
                k: v:在下一行来写对象的属性和值的关系;==注意缩进==
                对象也是k: v的方式

friends:
    name: sunwukong
    gender: male

     行内写法:

friends: {name: zhubajie,gender: female}

        数组(List,Set):用- 值表示数组中的一个元素

pets:
    - cat
    - pig
    - dog

        行内写法:

pets: [cat,pig,dog]

8.3.配置文件值注入

        javaBean:

/** 
 * @ConfigurationProperties:将配置文件定义的对象,映射到当前类 
 * prefix="person"是告诉SpringBoot把配置文件哪个对象映射到当前类中 
 * @author lenovo 
 * 
*/
@Component
@ConfigurationProperties(prefix="person")
public class Person {    
    private String name;    
    private Integer age;    
    private String gender;    
    private Date birthday;        
    private Map<String,Object> map;    
    private List<String> list;    
    private Horse horse;
}

编写配置文件:application.yml

person:
    name: tangseng
    age: 18
    gender: male
    birthday: 2021/4/13
    map: {mudidi: 西天,shijian: 取经}
    list:
      - 孙悟空
      - 猪八戒
      - 沙僧
    horse: 
       name: 白龙马
       gender: male

导入配置文件处理器依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

==重要提示:lastName与last-name效果一样==

9.配置properties文件

9.1.配置文件乱码

        修改Spring Properties File文件编码格式,方便在properties文件中输入中文,如果出现下图所示

        需要修改编码格式(之前已经修改过):


 9.2.编写properties文件

         注释掉application.yaml里面的内容,并且配置application.properties文件内容如下

#配置中文
person.last-name=唐僧
person.age=18
person.gender=male
person.birthday=2021/4/14
person.map.nudidi=西天
person.map.shijian=取经
person.list=孙悟空,猪八戒,沙僧
person.horse.name=白龙马
person.horse.gender=male

9.3.运行程序如下图所示

 9.4.解决内容乱码问题

        临时解决方案:上网找一个在线转换ASCII的编码格式;
        例如:在线编码转换

#配置中文
person.last-name=\u5510\u50e7
person.age=18
person.gender=male
person.birthday=2021/4/14
person.map.nudidi=\u897f\u5929
person.map.shijian=\u53d6\u7ecf
person.list=\u5b59\u609f\u7a7a,\u732a\u516b\u6212,\u6c99\u50e7
person.horse.name=\u767d\u9f99\u9a6c
person.horse.gender=male

9.5.输出内容如下

9.5.1.@Value获取值的使用,@Value使用方法

        在获取配置文件注入值的方法,我们还可以使用@Value(),可以直接获取配置文件的值,还可以进行SpEl(Spring表达式语言【方言】),还可以直接指定值,代码如下:

@Component
//@ConfigurationProperties(prefix="person")
public class Person {
	@Value("${person.last-name}")
	private String lastName;
	@Value("#{6 * 4}")
	private Integer age;
	@Value("female")
}

9.5.2.两者区别

        @Value和@ConfigurationProperties(prefix="")区别

@ConfigurationProperties()@Value
功能 批量映射注入写一个映射注入一个,不写不注入
松散绑定 支持不支持
SpEL 不支持支持
JSR303数据校验 支持不支持
复杂类型封装 支持不支持

JSR303数据校验
        ==高版本必须加入JSR303数据校验依赖,低版本可以不添加依赖:==

<!-- 导入JSR303数据校验的依赖(高版本必须添加此以来) -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Java代码如下:

@Component
@ConfigurationProperties(prefix="person")
@Validated
public class Person {
	
	@Email
	//@Value("${person.lastName}")
	private String lastName;
	//@Value("#{6 * 4}")
	private Integer age;
	//@Value("female")
}

        运行结果表示@ConfigurationProperties()支持JSR303数据校验,如图所示:

         配置yml和Properties都可以获取到值
        如果我们只是单一的获取配置文件某个值时候,推荐使用@Value
        如果是对JavaBean对象和配置文件进行映射时,推荐使用@ConfigurationProperties()

9.5.3.单一的获取配置文件

        Java代码如下:

@RestController
public class SayHelloControll {
	
	@Value("${person.last-name}")
	String name;
	@RequestMapping("hello")
	public String sayHello() {
		return "你好!" + name;
	}

}

9.5.4.@PropertySource&@ImportResource&@Bean

        @PropertySource:加载指定的配置文件;
        注释掉application.properties文件中的配置信息,并且创建person.properties文件

person.last-name=\u5510\u50e7
person.age=18
person.gender=male
person.birthday=2021/4/14
person.map.nudidi=\u897f\u5929
person.map.shijian=\u53d6\u7ecf
person.list=\u5b59\u609f\u7a7a,\u732a\u516b\u6212,\u6c99\u50e7
person.horse.name=\u767d\u9f99\u9a6c
person.horse.gender=male

        在Person.java文件中加入@PropertySource(value = { "classpath:person.properties" }),Java代码如下:

@PropertySource(value = { "classpath:person.properties" })
@Component
@ConfigurationProperties(prefix="person")
//@Validated
public class Person {
	
	//@Email
	//@Value("${person.last-name}")
	private String lastName;
	//@Value("#{6 * 4}")
	private Integer age;
	//@Value("female")
	private String gender;
	private Date birthday;
	
	private Map<String,Object> map;
	private List<String> list;
	//@Value("${person.horse}")
	private Horse horse;
}

        @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效;
创建beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="HelloService" class="com.wjz.services.HelloService"></bean>

</beans>

根据beans.xml文件创建对应的HelloService类

package com.wjz.services;

public class HelloService {

}

获取Spring容器对象,通过ioc.containsBean();方法校验是否存在此对象

    @Autowired
	ApplicationContext ioc;
	
	@Test
	public void testHelloService() {
		
		boolean flag = ioc.containsBean("helloService");
		System.out.println(flag);
		
	}

        Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上

@ImportResource(locations= {"classpath:beans.xml"})
@SpringBootApplication
public class MySpringBootDemo04Application {

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

SpringBoot不推荐编写Spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="HelloService" class="com.wjz.services.HelloService"></bean>

</beans>

SpringBoot推荐给容器中添加组件的方式;推荐使用全注解的方式
        配置类@Configuration------>Spring配置文件(可以在MySpringBootDemo04Application,一般情况创建自己的配置类)
        com.school下创建config,创建自己的MyAppConfig类
使用@Bean给容器中添加组件

/**
 * @Configuration:指明这是一个配置类;就是用来替代以前的xml配置文件
 * 在配置文件中是通过<bean></bean>标签添加组件(对象)
 * @author lenovo
 */
@Configuration
public class MyAppConfig {
	
	/**
	 * 将方法创建的对象,添加到组件中
	 * @return
	 */
	@Bean
	public HelloService helloService() {
		System.out.println("@Bean成功添加组件到容器中!");
		return new HelloService();
	}

}

9.5.5.配置文件占位符

        1、随机数

${random.value}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}

        2、指定默认值:

person.lastName=唐僧${random.uuid}
person.age=${random.int(100)}
person.gender=male
person.birthday=2021/4/15
person.map.mudidi=西天
person.map.shijian=取经
person.list=[孙悟空,猪八戒,沙僧]
person.horse.name=${person.horseName:小白龙}_马
person.horse.gender=male

9.5.6.profile

        1、多profile文件
                
在编写著配置文件时,文件名可以是application-[profile].properties/yml
                ==properties、yaml、yml文件优先级:
                ====properties>yaml>yml==
        2、yml的多文档模块

server:
  port: 8085
  
#指定使用哪个环境  
spring:
  profiles:
    active: dev
    
---

server:
  port: 8086
#声明是开发环境
spring:
  profiles: dev
  
---

server:
  port: 8087
#声明是生产环境
spring:
  profiles: prod

        3、指定激活相关profile
                1、properties文件:
在application.properties文件中指定激活:

spring.profiles.active=prod

                2、yml文件:在application.yml文件中指定激活:

spring:
  profiles:
    active: dev

                3.命令行:
                        java -jar springboot-0.0.1-SNAPSHOT.jar
                                --spring.profiles.active=dev;
                        可以直接在测试的时候,program arguments传入参数:
                                 --spring.profiles.active=prod

                     在VM arguments虚拟机参数的设置:
                                    -Dspring.profiles.active=prod

10. 配置文件加载顺序

配置文件优先级从两大方面先进行排序:
        项目根目录下的配置文件优先级最高,而class path下的配置文件优先级次之;
        同目录下的config文件中的配置文件优先级高:
                项目根目录下的config中的配置文件优先级高于根目录下的配置文件
                classpath下的config中的配置文件优先级高于classpath根目录下的配置文件
==当四个目录下都有配置文件时,相同配置会被优先级最高的配置文件覆盖,不同配置会进行互补,而不是覆盖!==
当使用命令行启动项目时,命令行优先级最高,选取配置文件的参数时同上。

11.所有的配置加载顺序

        SpringBoot也可以从以下位置加载配置; 优先级从高到低;高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置。

11.1.命令行参数

        所有的配置都可以在命令行上进行指定
                java -jar SpringBootDemo02-0.0.1-SNAPSHOT.jar --server.port=8090 --server.servlet.context-path=/spb
注意:
        
==Spring Boot1.x版本设置路径:--server.context-path=/spb==
        ==SpringBoot2.x版本设置路径:--server.servlet.context-path=/spb==
        多个配置用空格分开; --配置项=值

11.2.由jar包外向jar包内进行寻找;优先加载带profile

        jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
        jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件

11.3.再来加载不带profile

        jar包外部的application.properties或application.yml(不带spring.profile)配置文件
        jar包内部的application.properties或application.yml(不带spring.profile)配置文件
        所有支持的配置加载来自于:
Spring Boot Reference Guide

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值