Spring Boot入门

1.微服务

一个项目可以由多个小型服务(微服务)构成

把各个功能变成独立的项目,再通过协议(例如HTTP等)将独立的项目连在一块

如果需要对某个功能进行修改,只需对单独的项目进行修改,不涉及其它项目正常运行等问题

2.Spring Boot作用

(1)可以快速开发微服务模块

(2)简化J2EE开发(用Java开发大型项目)

(3)整个Spring技术栈的整合(整合SpringMVC、Spring等)

(4)整个J2EE技术的整合(整合MyBatis、Redis等)

3.准备工作

(1)配置jdk

①方式一

JAVA_HOME:D:\Java\jdk1.8.0_241

Path:%JAVA_HOME%\bin

CLASS_PATH:.;$%JAVA_HOME%\bin(可以不配置)

②方式二

直接配置Path

Path:D:\Java\jdk1.8.0_241\bin

(2)配置maven

①方式一

MAVEN_HOME:maven根目录

Path:%MAVEN_HOME%\bin

②方式二

Path:D:\apache-maven-3.6.3\bin

(3)配置maven本地仓库

通过自行下载的maven去导入Spring Boot环境,也可以使用IDEA等工具自带的maven(不建议这样做)

D:\apache-maven-3.6.3\conf:setting.xml

<localRepository>D:/mavenstore</localRepository>

4.开发工具

Eclipse(安装STS插件)

STS

IntelliJ IDEA(推荐)

5.目录结构resources

static:静态资源(js、css、图片、音频、视频等)

templates:模板文件(模版引擎:freemarker、thymeleaf;默认不支持jsp)

application.properties:配置文件(对端口号等服务端信息进行配置)

6.Spring Boot构建web项目

Spring Boot内置了tomcat,并且不需要打成war包再执行,可以直接执行jar包

Spring Boot将各个应用/三方框架设置成了一个个“场景”stater,以后要用哪个,只需要引入哪个场景即可

选完之后,Spring Boot就会将该场景所需要的所有依赖自动注入

例如:选择“web”,Spring Boot就会将web相关的依赖(tomcat、json等等)全部引入本项目

7.主要注解

(1)@SpringBootApplication

@SpringBootApplication注解包含@SpringBootConfiguration、@EnableAutoConfiguration

@SpringBootApplication:Spring Boot的主配置类

(2)@SpringBootConfiguration

@SpringBootConfiguration:包含@Configuration,表示配置类,用来代替配置文件

该类是一个配置类,加了@Configuration注解的类,会自动纳入Spring容器

在Spring中通过@Component注解自动纳入,在Spring Boot中可以通过@Configuration注解实现自动纳入

(3)@EnableAutoConfiguration

@EnableAutoConfiguration:使Spring Boot可以自动配置:可以找到@SpringBootApplication所在类的包,就会将该包及所有的子包全部纳入Spring容器

传统的方法

将controller包,手动写到scan扫描器中(即加入Spring容器中)

Spring Boot

通过@AutoConfigurationPackage自动配置自己写的类

通过@Import(AutoConfigurationImportSelector.class)自动装配第三方jar

8.配置文件

(1)作用

Spring Boot是自动配置的(约定:端口号是8080等等),但是可以使用配置文件对默认的配置进行修改

(2)类型

①xml

是一个标记文档

<server>
	<port>8080</port>
	<path>/a/b/c</path>
</server>
②application.properties

k=v

③application.yml

不是一个标记文档

A.application.yml
server:
  port: 8080
  
student: 
  name: hzb
  age: 21
  sex: true
  birthday: 2020/8/7
#  location: 
#    province: 山西
#    city: 太原
#    zone: 尖草坪区


  location: {province: '山西', city: "太原", zone: 尖草坪区}
#  hobbies: 
#    - 足球
#    - 篮球
  hobbies: [足球, 篮球]
#  skills:
#    - Java
#    - python
  skills: [Java, python]
#  pet:
#    nickName: bxd 
#    strain: td
  pet: {nickName: bxd, strain: td}

a.k:空格v

b.通过垂直对齐指定层次关系

c.默认可以不写引号,如果要写"",则会将其中的转义符进行转义,其他不会

server:
  port: 8080
  
student: 
  name: hzb
  age: 21
  sex: true
  birthday: 2020/8/7
  location: {province: '山西', city: "太原", zone: 尖草坪区}
  hobbies: [足球, 篮球]
  skills: [Java, python]
  pet: {nickName: bxd, strain: td}
B.entity
package nuc.hzb.demo.entity;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component // 将此JavaBean纳入Spring容器
@ConfigurationProperties(prefix = "student")
public class Student {
	
	private String name;
	private int age;
	private boolean sex;
	private Date birthday;
	private Map<String, Object> location;
	private String[] hobbies;
	private List<String> skills;
	private Pet pet;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public boolean isSex() {
		return sex;
	}
	public void setSex(boolean sex) {
		this.sex = sex;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public Map<String, Object> getLocation() {
		return location;
	}
	public void setLocation(Map<String, Object> location) {
		this.location = location;
	}
	public String[] getHobbies() {
		return hobbies;
	}
	public void setHobbies(String[] hobbies) {
		this.hobbies = hobbies;
	}
	public List<String> getSkills() {
		return skills;
	}
	public void setSkills(List<String> skills) {
		this.skills = skills;
	}
	public Pet getPet() {
		return pet;
	}
	public void setPet(Pet pet) {
		this.pet = pet;
	}
	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + ", sex=" + sex + ", birthday=" + birthday + ", location="
				+ location + ", hobbies=" + Arrays.toString(hobbies) + ", skills=" + skills + ", pet=" + pet + "]";
	}
}
<!--没有该依赖也可以,但是由于使用了@ConfigurationProperties会有红色警告-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
package nuc.hzb.demo.entity;

public class Pet {
	private String nickName;
	private String strain;
	public String getNickName() {
		return nickName;
	}
	public void setNickName(String nickName) {
		this.nickName = nickName;
	}
	public String getStrain() {
		return strain;
	}
	public void setStrain(String strain) {
		this.strain = strain;
	}
	@Override
	public String toString() {
		return "Pet [nickName=" + nickName + ", strain=" + strain + "]";
	}
}
C.HelloWorldApplicationTests
package nuc.hzb.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import nuc.hzb.demo.entity.Student;

@SpringBootTest
class HelloWorldApplicationTests {

	@Autowired
	Student student;
	
	@Test
	void contextLoads() {
		System.out.println(student);
	}

}
D.注意

集合、数组:中括号

Map、对象的属性:大括号

中括号可以省略,但是大括号不可以省略

9.绑定

(1)方式一

@ConfigurationProperties(与properties/yml文件有关)

@ConfigurationProperties(prefix = “student”)

(2)方式二

@Value(“xxx”)

@Value("hzbhzb")
private String name;

(3)注意

二者可以互补

@ConfigurationProperties优先级高于@Value(“xxx”)

(4)区别

@ConfigurationProperties@Value
注值批量注入单个注入
松散语法支持(nickName等价于nick-name)不支持
SpEL(Spring表达式语言)不支持支持
JSR303数据校验支持不支持
注入复杂类型支持不支持

JSR303数据校验,高版本的Spring Boot需要导入依赖

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
@Email
@Value("344728800")
private String email;
Property: student.email
Value: 344728800
Reason: 不是一个合法的电子邮件地址

10.@PropertySource

默认加载application.propertiesapplication.yml文件中的数据

@PropertySource(value = {“classpath:conf.properties”})加载conf.properties文件中的数据

@PropertySource只能加载properties,不能加载yml

...
@PropertySource(value = {"classpath:conf.properties"})
public class Student {
	...
}

11.配置

(1)xml配置文件

Spring Boot可以自动装配/自动配置

Spring等配置文件默认会被Spring Boot自动配置

如果自己编写Spring等配置文件,Spring Boot默认不识别

如果需要识别,则需要在Spring Boot主配置类上通过@ImportResource指定配置文件的路径

(但是不推荐手写Spring配置文件)

@ImportResource(locations = {"classpath:spring.xml"})
package nuc.hzb.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;

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

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

}
package nuc.hzb.demo.service;

public class StudentService {

}
<?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="studentService" class="nuc.hzb.demo.service.StudentService">
	</bean>

</beans>

配置的方式有两种:xml配置文件、注解方式配置

(2)注解方式配置

Spring Boot推荐使用注解方式进行配置:写一个类,然后在类上加@Configuration、@Bean

package nuc.hzb.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import nuc.hzb.demo.service.StudentService;

@Configuration
public class Appconfig {
	@Bean
	public StudentService studentServiceConfig() {
		StudentService studentService = new StudentService();
		return studentService;
	}
}

测试

package nuc.hzb.demo;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;

import nuc.hzb.demo.entity.Student;
import nuc.hzb.demo.service.StudentService;

@SpringBootTest
class HelloWorldApplicationTests {
	
	@Autowired
	ApplicationContext context;
	
	@Test
	void contextLoads() {
		System.out.println(context.getBean("studentService", StudentService.class));
		System.out.println(context.getBean("studentServiceConfig", StudentService.class));
	}

}

(3)注入属性示例

package nuc.hzb.demo.dao;

public class StudentDao {

}
package nuc.hzb.demo.service;

import nuc.hzb.demo.dao.StudentDao;

public class StudentService {
	
	private StudentDao studentDao;

	public StudentDao getStudentDao() {
		return studentDao;
	}

	public void setStudentDao(StudentDao studentDao) {
		this.studentDao = studentDao;
	}
	
}
package nuc.hzb.demo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import nuc.hzb.demo.dao.StudentDao;
import nuc.hzb.demo.service.StudentService;

@Configuration
public class Appconfig {
	@Bean
	public StudentService studentServiceConfig() {
		StudentService studentService = new StudentService();
		StudentDao studentDao = new StudentDao();
		studentService.setStudentDao(studentDao);
		return studentService;
	}
}

12.占位符表达式

(1)随机数

${random.uuid}:uuid

${random.value}:随机字符串

(2)引用变量值

application.properties

student.user.name=298

application.yml

student: 
  ...
  name: ${student.user.name:没找到student.user.name}

实际引用的是properties中的student.user.name=298

如果不存在student.user.name,则name=没找到student.user.name(默认值)

13.多环境设置及切换

(1)properties

默认boot会读取application.properties环境8081

多个:

application-环境名.properties

application-dev.properties8082

application-test.properties8083

如果要选择某一个具体的环境: application.properties中指定:spring.profiles.active=环境名

spring.profiles.active=dev

如果将application.properties注释掉,spring boot仍然会读取其他appilcation-环境名.properties中的配置

properties的优先级高于yml

(2)yml

server:
  port: 8081
#当打成jar包时,不在默认环境下去指定而是通过命令行执行jar包的时候去指定允许环境
#spring:
#  profiles:
#    active: dev
---
server:
  port: 8082
spring:
  profiles: dev

---
server:
  port: 8083
spring:
  profiles: test

(3)动态切换环境

①通过命令行方式的运行参数指定环境
java -jar 项目名.jar --spring.profiles.active=环境名
②使用开发工具去指定环境

14.配置文件的位置

(1)项目内部的配置文件

properties和yml中的配置,相互补充;如果冲突,则properties优先级高

Spring Boot默认能够读取的application.properties/application.yml,这2个文件可以存在于以下4个地方:

file项目根目录/config:application.properties

file项目根目录:application.properties

classpath项目根目录/config:application.properties

classpath项目根目录:application.properties

(2)注意

如果某项配置冲突,则优先级从上往下

如果不冲突,则互补结合使用(四个位置的都可以使用)

补充了解,通过命令行调用外部配置文件:java -jar 项目.jar --spring.config.location=D:/application.properties

外部配置文件的作用就是补救,在打好jar包后需要修改端口号、项目路径等

如果同一个配置同时存在于内部配置文件外部配置文件,则外部配置文件优先级>内部配置文件优先级

通过命令行配置运行参数:java -jar 项目.jar --server.port=8884(如果个别需要改动,则不需要外加配置文件,直接通过运行参数补救即可)

多个地方配置时如果冲突,优先级:命令参数(运行参数>调用外部的配置文件)>内部文件 (properties>yaml)

官网配置说明:https://docs.spring.io/spring-boot/docs/2.3.3.RELEASE/reference/htmlsingle/#boot-features-external-config

15.日志

(1)生成日志

日志框架:log4j、log4j2、slf4j、logback、UCL、JUL 、jboss-logging等

Spring Boot默认选用slf4j,logback

Spring Boot默认帮我们配置好了日志,我们直接使用即可

日志级别:TRACE< DEBUG< INFO<WARN< ERROR< FATAL<OFF

Spring Boot默认的日志级别是info(即只打印info及之后级别的信息)

  • 也可以自定义级别:全局配置文件中logging.level.nuc.hzb.demo=warn ,即logging.level.主配置类所在包=级别

  • 可以通过配置将日志信息存储到文件中logging.file.name=spring.log存储到了项目的根目录中的spring.log

  • 也可以指定具体的日志路径:略

  • 也可以存储到一个文件夹中:略

(2)指定日志显示格式

①日志显示在console中
logging.pattern.console=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} -%msg%n
#    %d:日期时间
#    %thread:线程名
#    %-5level:显示日志级别,-5表示从左显示5个字符宽度
#    %logger{50}:设置日志长度,例如o.s.w.s.m.m.a.
#    %msg:日志消息
#    %n:回车
②日志显示在文件中
logging.pattern.file=%d{yyyy-MM-dd} [%thread] %-5level %logger{50} %msg%n

默认的日志格式,是在jar包中相应包的xml文件中进行配置

官网日志说明https://docs.spring.io/spring-boot/docs/2.3.3.RELEASE/reference/htmlsingle/#boot-features-custom-log-configuration

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值