深入源码底层——SpringBoot自动装配-自定义Start

SpringBoot自动装配

在没有使用SpringBoot之前,使用ssm时配置redis需要在XML中配置端口号,地址,账号密码,连接池等等,而使用了SpringBoot后只需要在application.yml或application.properties中配置信息,然后在pom文件添加一个Redis的start就可以用了

SpringBootApplication注解

什么是自动装配,也就是说帮你把需要的类自动添加到Spring容器中

只要是一个SpringBoot项目肯定有这样一个类

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(TokenApplication.class, args);
    }
}			

而自动装配是在@SpringBootApplication这个注解中实现的,点进去首先能看到这个注解上还有三个类

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {}

其中SpringBootConfiguration上还有一个注解@Configuration也就是说明其实SpringBootApplication也是一个配置类

@ComponentScan用于扫描需要被Spring管理的类,这也就是为什么写的类需要在SpringBoot启动类同级或在同级下的子包中

@EnableAutoConfiguration点进去发现它上面有一个特殊的注解@Import(AutoConfigurationImportSelector.class)

@Import注解的作用是将指定类添加到Spring容器中成为一个Bean

而在AutoConfigurationSelector类中有自动装配的实现

	@Override
	public String[] selectImports(AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return NO_IMPORTS;
		}
		AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(annotationMetadata);
		return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
	}
protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
    if (!isEnabled(annotationMetadata)) {
        return EMPTY_ENTRY;
    }
    //下面的方法
    AnnotationAttributes attributes = getAttributes(annotationMetadata);
    List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
    configurations = removeDuplicates(configurations);
    Set<String> exclusions = getExclusions(annotationMetadata, attributes);
    checkExcludedClasses(configurations, exclusions);
    configurations.removeAll(exclusions);
    configurations = getConfigurationClassFilter().filter(configurations);
    fireAutoConfigurationImportEvents(configurations, exclusions);
    return new AutoConf
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值