springboot简介
springboot是用来简化spring应用开发的一个框架,是对spring整个技术栈的整合,是J2EE一站式解决方案。它可以自动配置spring的开发环境。口号是“约定大于配置”。
微服务简介
微服务是一种架构风格。一组小型服务可以通过HTTP进行互通。每一个功能元素最终都是一个可独立替换、独立升级的软件单元。
springboot打包
- 在pom.xml中加入springboot的maven插件:
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
但是我用的STS帮我自动加上了。哈哈哈。
- 在项目中使用maven clean
- 使用maven build(第二个),Goals中填package,记得勾skip tests
springboot版本仲裁中心
在pom.xml中我们可以看到这样的父文件标签:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
进入后可以看到这样的父文件标签:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath>../../spring-boot-dependencies</relativePath>
</parent>
最终我们可以进入artifictId为:<artifactId>spring-boot-dependencies</artifactId>
的xml文件中。这就是springboot版本仲裁中心。可以看到,这里面声明的都是版本号,所以我们添加依赖时不需要添加版本号,除非不在版本仲裁中心管理范围之内。
导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
以此为例。artifictId为spring-boot-starter-web,spring-boot-starter意为springboot场景启动器;整个意为web方面的springboot场景启动器。什么是场景启动器呢?场景启动器就是在某个场景需要某些依赖,springboot帮我们把这些依赖整合起来,由此形成的一个组合。stater有很多,遇到什么场景,就引入哪个starter
@SpringBootApplication自动配置
@SpringBootApplication注解了这是一个springboot项目。查看源码,其中有一堆注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
我们来说说其中一个:
@EnableAutoConfiguration:启动自动配置。其中也有一堆注解:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
要说的是@AutoConfigurationPackage:自动配置包,查看源码,有这一行:@Import(AutoConfigurationPackages.Registrar.class),导入组件。导入什么呢?导入经过AutoConfigurationPackages.Registrar扫描主配置类所在文件夹及其子文件夹中的所有组件。
@EnableAutoConfiguration中还有一个注解:@Import(AutoConfigurationImportSelector.class)导入AutoConfigurationImportSelector,自动配置导包选择器。选择的类会在selectImports()方法中被以类名的方式被放入String[]。其中有这样的方法protected List getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes)调用了这么一个方法SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),getBeanClassLoader()),属于SpringFactoriesLoader,他会从properties文件中拿出Factory的名字。
public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
这就是类路径