SpringBootQuickStart
SpringBootQuickStart
Tinsiag ZhuSpring Boot 入门
1. 基础
boot 工程的父工程, 用于管理起步依赖的管理
pom.xml
<parent>
xxx
</parent>
创建Maven工程
导入spring-boot-starter-web起步依赖
编写Controller
提供启动类
2. 配置
application.properties[官方文档](Common Application Properties :: Spring Boot)
spring.application.name=spring-boot-quick-start server.port=8081 //端口 debug=true //debug server.servlet.context-path=/fuck //虚拟目录application.yml实际开发中使用server: port: 9191 servlet: context-path: /91 debug: true
3. yml配置信息书写与获取
配置文件的书写
email: user: xxx@qq.com code: xxx host: smtp.qq.com auth: true配置文件的获取
@Value("${键名}")public class EmailProperties{ @Value("${email.user}") public String user; @Value("${email.code}") public String code; @Value("${email.host}") public String Value; @Value("${email.auth}") public String auth; .... }@ConfigurationProperties(Prefix="前缀")要求配置文件中的键名与实体类对应的成员变量要相同
@ConfigurationProperties(Prefix="email") public class EmailProperties{ public String user; public String code; public String Value; public String auth; .... }
4. Bean管理
什么是JavaBean?
JavaBean 是一种遵循特定编写规范的 Java 类。JavaBean 就是一个用来“存数据”的标准 Java 类。只要你看到一个类全是
private属性,并且配对了一堆get/set方法,它基本上就是一个 JavaBean。
Bean扫描
使用标签
<context:component0scan base-package="com.tinsiag"/>使用注解
@ComponentScan(basePackages="com.tinsiag")@SpringBootApplication里包含@ComponentScan
5. Bean注册
| 注解 | 说明 | 位置 |
|---|---|---|
| @Component | 声明bean的基础注释 | 不属于以下三类,用此注释 |
| @Controller | @Component的衍生注解 | 标注在控制器上的类 |
| @Service | @Component的衍生注解 | 标注在业务类上 |
| @Respository | @Component的衍生注解 | 标注在数据访问类上(由于mybatis整合,用的少) |
如果要注册Bean对象来自于第三方(不是自定义的),是无法用@Component及衍生的注解声明Bean的
@Bean如果要注册第三方Bean,建议在配置类中集中注册
@Configuration public class CommonConfig { @Bean public Resolver resolver(){ return new Resolver(); } }对象默认的名字是方法名
System.out.println(context.getBean("province"));@Bean public Province province(){ return new Province(); }改对象名字
@Bean("aa")如果方法内部的容器中需要使用ioc容器已经存在的Bean对象,那么只需要在方法上声明即可,spring会自动注入
public Province province(Country country){ system.out.println("Province: " + Country ); return new Province(); }终端输出
Province: Country{name='null', system='null'}@ImportImport(Xxx.class)导入配置类 : 有多个配置类可使用数组来导入
Import({Xxx.class,xxx.class})导入
ImportSelector接口实现类CommonImportSelector.class
package com.tinsiag.config; import org.springframework.context.annotation.ImportSelector; import org.springframework.core.type.AnnotationMetadata; public class CommonImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[]{"com.tinsiag.springbeanregister.config.CommonConfig"}; } }导入 使用
@Import(CommonImportSelector.class)高级版写法:
public class CommonImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { //读取配置文件的内容 List<String> imports = new ArrayList<>(); InputStream is = CommonImportSelector.class.getClassLoader().getResourceAsStream("common.imports"); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = null; try { while ((line= br.readLine())!= null){ imports.add(line); } } catch (IOException e) { throw new RuntimeException(e); } finally { if(br!= null){ try { br.close(); } catch (IOException e) { throw new RuntimeException(e); } } } return imports.toArray(new String[0]); } }@Enablexxxx注解,封装@Import注解: 创建Annotation类
package com.tinsiag.anno; import com.tinsiag.config.CommonConfig; import org.springframework.context.annotation.Import; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Import(CommonConfig.class) public @interface EnableCommonConfig { }
6. Bean注册条件
SpringBoot 提供了一个设置注册生效条件的注解@Conditional
常用注解
| 注解 | 说明 |
|---|---|
| @ConditionalOnProperty | 配置文件中存在对应的属性,才声明该Bean |
| @ConditionalOnMissingBean | 当不存在当前类型的Bean时,才声明该Bean |
| @ConditionalOnClass | 当前环境存在指定的这个类时,才声明该Bean |
@ConditionalOnProperty如果配置文件中配置了指定的信息,则注入,否则不注入
@Bean @ConditionalOnProperty(prefix = "country",name = {"name","system"}) public Country country(@Value("${country.name}") String name,@Value("${country.system}")String system){ Country country = new Country(); country.setName(name); country.setSystem(system); return country; }@ConditionalOnMissingBean如果IOC容器中不存在Country,则注入Province,否则不注入
@ConditionalOnMissingBean(Country.class)@ConditionalOnClass如果当前环境中存在xxx类,则注入Province,否则不注入
下面以DispatcherServlet为例:
什么是DispatcherServlet?
DispatcherServlet 是 Spring MVC 框架的核心组件,被称为 “前端控制器” (Front Controller)。
简单来说,它是整个 Spring Web 应用的中央调度员。所有的 HTTP 请求(Request)都会先发送给它,然后由它负责分发给具体的代码(Controller)去处理。
@ConditionalOnClass(name = "org.springframework.web.servlet.DispatcherServlet")
7. 自动配置
源码分析:
String[] selectImport(...)
SpringBoot 自动配置原理
- 在主启动类上添加SpringBootApplication注解,这个注解组合了EnableAutoConfiguration注解
- EnableAutoConfiguration注解又组合了Import注解,导入了AutoConfigurationImportSelector类
- 实现selectImports方法,这个方法经过层层调用,最终会读取到META-INF目录下的 后缀名为imports的文件,当然了,boot2.7以前的版本,读取的是spring.factories文件
8. 自定义starter
在实际开发中,经常会定义一些公共组件,提供给各个项目团队使用。而在SpringBoot的项目中,一般会将这些公共组件封装为SpringBoot 的starter
依赖管理功能
自动配置功能
需求
- 需求:自定义mybatis的starter
步骤
- 创建
dmybatis-spring-boot-autoconfigure模块,提供自动配置功能,并自定义配置文件 META-INF/Spring/xxxx.imports - 创建
dmybatis-spring-boot-starter模块,在starter中引入自动配置模块










