一、SpringBoot基础篇
1.SpringBoot初探
SpringBoot的初衷简化配置
2.SpringBoot项目的构建方式
2.1 通过官网自动生成
https://start.spring.io/ 快速生成
2.2 IDE 在线模板生成
本质上和上面是一样的,只是简化了我们的操作
2.3 IDE通过maven项目构建
1.创建一个独立的web项目
2.引入对应依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.15.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3.添加对应的启动器
@SpringBootApplication
public class GpSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(GpSpringBootApplication.class,args);
}
}
4.启动启动器的主方法
测试即可
3.SpringBoot中的常规配置
3.1 入口类和相关注解
@SpringBootApplication
public class GpSpringbootDemo02Application {
public static void main(String[] args) {
// Spring IoC 容器的初始化
ApplicationContext ac = SpringApplication.run(GpSpringbootDemo02Application.class, args);
}
}
main方法:
其实完成的就是一个SpringIoC容器的初始化操作
@SpringBootApplication注解
1.在IoC初始化的时候会加载该注解
2.是一个组合注解
@Target({ElementType.TYPE}) // 注解可以写在哪些地方
@Retention(RetentionPolicy.RUNTIME) // 该注解的作用域 RESOURCES CLASS RUNTIME
@Documented // 该注解会被API抽取
@Inherited // 可继承
// 以上四个是Java中提供的元注解
@SpringBootConfiguration // 本质上就是一个Configuration注解
@EnableAutoConfiguration // 自动装配的注解
@ComponentScan( // 扫描 会自动扫描 @SpringBootApplication所在的类的同级包(com.gupaoedu)以及子包中的Bean,所有一般我们建议将入口类放置在 groupId+artifcatID的组合包下
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
3.2 Banner
http://patorjk.com/software/taag (在线生成文字图标地址)
在resources目录下创建一个 banner.txt
文件
关闭Banner
public static void main(String[] args) {
// Spring IoC 容器的初始化
SpringApplication springApplication = new SpringApplication(GpDblSpringbootServletApplication.class);
springApplication.setBannerMode(Banner.Mode.OFF);// 关闭Banner
springApplication.run(args);
}
3.3 常规配置
在SpringBoot中给我们提供的有两个配置文件 applicationContext.properties,applicationContext.yml 作用是一样的,一个项目中只需要其中的一个就可以了。
Tomcat配置修改
server.port=8082
server.servlet.context-path=/springboot
自定义的属性
# 自定义的配置信息
user.username=dbl
user.age=18
user.address=成都
获取
@Value("${user.username}")
private String userName;
@Value("${user.age}")
private Integer age;
@Value("${user.address}")
private String address;
中文乱码问题
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
类型安全配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
package com.gp.dbl.bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* descrription:
* <p>
* Create by DbL on 2020/10/25
*/
@Component
// 属性文件中的属性和User对象中的成员变量映射
@ConfigurationProperties(prefix = "user")
public class User {
private String username;
private Integer age;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
}
3.4 Logback日志
SpringBoot内置的有Logback的依赖
直接在属性文件中简单配置
# logback的配置
logging.file=d:/log.log
logging.level.org.springframework.web=DEBUG
单独提供一个logback.xml
3.5 Profile
命名规则application-xxx.properties
spring.profiles.active=xxx # 指定对应的环境
4.SpringBoot中的静态资源
4.1 static目录
SpringBoot默认的存放静态资源的目录
4.2 webapp目录
在resources同级目录下创建一个webapp目录,该目录的类型必须是ResourcesRoot
4.3 自定义静态资源路径
自定义目录后,创建对应的相关资源,然后在属性文件中去覆盖静态资源的路径配置即可
# 表示所有的访问都经过静态资源路径
spring.webflux.static-path-pattern=/**
# 覆盖默认的配置,所有需要将默认的static public等这些路径将不能作为静态资源的访问
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/custom
5.自动装配的原理
5.1 starter
名称 | 描述 |
---|---|
spring-boot-starter-thymeleaf | 使MVC Web applications 支持Thymeleaf |
spring-boot-starter-data-couchbase | 使用Couchbase 文件存储数据库、Spring Data Couchbase |
spring-boot-starter-artemis | 为JMS messaging使用Apache Artemis |
spring-boot-starter-web-services | 使用Spring Web Services |
spring-boot-starter-mail | Java Mail、Spring email为邮件发送工具 |
spring-boot-starter-data-redis | 通过Spring Data Redis 、Jedis client使用Redis键值存储数据库 |
spring-boot-starter-web | 构建Web,包含RESTful风格框架SpringMVC和默认的嵌入式容器Tomcat |
spring-boot-starter-activemq | 为JMS使用Apache ActiveMQ |
spring-boot-starter-data-elasticsearch | 使用Elasticsearch、analytics engine、Spring Data Elasticsearch |
spring-boot-starter-integration | 使用Spring Integration |
spring-boot-starter-test | 测试 Spring Boot applications包含JUnit、 Hamcrest、Mockito |
spring-boot-starter-jdbc | 通过 Tomcat JDBC 连接池使用JDBC |
spring-boot-starter-mobile | 通过Spring Mobile构建Web应用 |
spring-boot-starter-validation | 通过Hibernate Validator使用 Java Bean Validation |
spring-boot-starter-hateoas | 使用Spring MVC、Spring HATEOAS构建 hypermedia-based RESTful Web 应用 |
spring-boot-starter-jersey | 通过 JAX-RS、Jersey构建 RESTful web applications;spring-boot-starter-web的另一替代方案 |
spring-boot-starter-data-neo4j | 使用Neo4j图形数据库、Spring Data Neo4j |
spring-boot-starter-websocket | 使用Spring WebSocket构建 WebSocket 应用 |
spring-boot-starter-aop | 通过Spring AOP、AspectJ面向切面编程 |
spring-boot-starter-amqp | 使用Spring AMQP、Rabbit MQ |
spring-boot-starter-data-cassandra | 使用Cassandra分布式数据库、Spring Data Cassandra |
spring-boot-starter-social-facebook | 使用 Spring Social Facebook |
spring-boot-starter-jta-atomikos | 为 JTA 使用 Atomikos |
spring-boot-starter-security | 使用 Spring Security |
spring-boot-starter-mustache | 使MVC Web applications 支持Mustache |
spring-boot-starter-data-jpa | 通过 Hibernate 使用 Spring Data JPA (Spring-data-jpa依赖于Hibernate) |
spring-boot-starter | Core starter,包括 自动配置支持、 logging and YAML |
spring-boot-starter-groovy-templates | 使MVC Web applications 支持Groovy Templates |
spring-boot-starter-freemarker | 使MVC Web applications 支持 FreeMarker |
spring-boot-starter-batch | 使用Spring Batch |
spring-boot-starter-social-linkedin | 使用Spring Social LinkedIn |
spring-boot-starter-cache | 使用 Spring caching 支持 |
spring-boot-starter-data-solr | 通过 Spring Data Solr 使用 Apache Solr |
spring-boot-starter-data-mongodb | 使用 MongoDB 文件存储数据库、Spring Data MongoDB |
spring-boot-starter-jooq | 使用JOOQ链接SQL数据库;spring-boot-starter-data-jpa、spring-boot-starter-jdbc的另一替代方案 |
spring-boot-starter-jta-narayana | Spring Boot Narayana JTA Starter |
spring-boot-starter-cloud-connectors | 用连接简化的 Spring Cloud 连接器进行云服务就像Cloud Foundry、Heroku那样 |
spring-boot-starter-jta-bitronix | 为JTA transactions 使用 Bitronix |
spring-boot-starter-social-twitter | 使用 Spring Social Twitter |
spring-boot-starter-data-rest | 使用Spring Data REST 以 REST 方式暴露 Spring Data repositories |
spring-boot-starter-actuator | 使用Spring Boot Actuator 的 production-ready 功能来帮助你监视和管理应用 |
spring-boot-starter-undertow | 使用 Undertow 作为嵌入式服务容器;spring-boot-starter-tomcat的另一替代方案 |
spring-boot-starter-jetty | 使用 Jetty 作为嵌入式服务容器;spring-boot-starter-tomcat的另一替代方案 |
spring-boot-starter-logging | 为 logging 使用Logback.默认 logging starter |
spring-boot-starter-tomcat | 使用 Tomcat 作为嵌入式服务容器;作为默认嵌入式服务容器被spring-boot-starter-web使用 |
spring-boot-starter-log4j2 | 使用Log4j2记录日志;spring-boot-starter-logging的另一替代方案 |
5.2 自动装配
@EnableAutoConfiguration
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
通过@EnableAutoConfiguration注解发现。其本身就是一个组合注解,有一个注解我们必须要弄清楚@Import
注解
@Import
在Spring中我们将类型交给SpringIoC管理的方式有哪些?
1.基于xml配置文件
2.基于xml配置文件@Component
3.基于Java配置类【@Configuration】 @Bean
4.基于Java配置类+@ComponentScan+@Component
5.FactoryBean接口【getObject()】
6.@Import注解
第一种使用方式
静态使用方式
@Configuration
@Import(UserService.class)
public class JavaConfig {
/*@Bean
public UserService getUserSerivce(){
return new UserService();
}*/
}
在@Import注解中直接指定要添加的类型
缺点:直接在@Import中写死要注入的类型,不太灵活
第二种使用方式
ImportSelector接口
/**
* descrription:
* <p>
* Create by DbL on 2020/10/25
*/
public class GpDBLImportSelector implements ImportSelector {
/**
* 动态获取IoC要加载的类型
* @param annotationMetadata 注解的元数据
* @return
* IoC要加载的类型的数组
*/
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
// 根据不同的业务逻辑 实现动态添加IoC加载的类型
/*if (){
}*/
return new String[]{LoggerService.class.getName(),CacheService.class.getName()};
}
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(GpImportSelector.class)
public @interface EnableGpImport {
}
是将@Import注解中添加的 ImportSelector的实现类中的selectImports
这个方法返回的字符串数组加载到IoC容器中
第三种实现方式
实现ImportBeanDefinitionRegistrar接口,其实和第二种方式很类似,都是在源码设计层面用的比较多。
/**
* descrription:
* <p>
* Create by DbL on 2020/10/25
*/
public class GpDBLImportBeanDefinition implements ImportBeanDefinitionRegistrar {
/**
* 提供了一个beanDefinition的注册器,我直接把需要IoC加载的类型注册到容器中去
* @param annotationMetadata
* @param beanDefinitionRegistry beanDefinition的注册器
*/
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
// 将我们需要添加的类型统一封装为RootBeanDefinition对象
RootBeanDefinition cache = new RootBeanDefinition(CacheService.class);
beanDefinitionRegistry.registerBeanDefinition("cache",cache);
RootBeanDefinition logger = new RootBeanDefinition(LoggerService.class);
beanDefinitionRegistry.registerBeanDefinition("logger",logger);
}
}
原理分析
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return NO_IMPORTS;
} else {
// 加载META-INF/spring-autoconfigure-metadata.properties
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);
AutoConfigurationImportSelector.AutoConfigurationEntry autoConfigurationEntry = this.getAutoConfigurationEntry(autoConfigurationMetadata, annotationMetadata);
// 返回需要IoC加载的类型数组
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
}
protected AutoConfigurationImportSelector.AutoConfigurationEntry getAutoConfigurationEntry(AutoConfigurationMetadata autoConfigurationMetadata, AnnotationMetadata annotationMetadata) {
if (!this.isEnabled(annotationMetadata)) {
return EMPTY_ENTRY;
} else {
AnnotationAttributes attributes = this.getAttributes(annotationMetadata);
// 获取候选的配置信息 META-INF/spring.factories 加载了很多的 类路径
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
// 去掉重复的
configurations = this.removeDuplicates(configurations);
// 去掉要排除掉的类型
Set<String> exclusions = this.getExclusions(annotationMetadata, attributes);
this.checkExcludedClasses(configurations, exclusions);
configurations.removeAll(exclusions);
// 过滤器
configurations = this.filter(configurations, autoConfigurationMetadata);
// 广播
this.fireAutoConfigurationImportEvents(configurations, exclusions);
return new AutoConfigurationImportSelector.AutoConfigurationEntry(configurations, exclusions);
}
}
自动装配的原理:
1.在SpringBoot项目启动的时候,会加载SpringBootApplication这个注解
2.会解析@EnableAutoConfiguration注解
3.与之对应的解析@Import注解
4.执行ImportSelector接口的的实现
5.加载META-INF/spring-autoconfigure-metadata.properties中的注解元数据信息
6.加载META-INF/spring.factories各种类路径【第三方扩展也同样的会加载对应的文件 SPI扩展机制】