美文网首页
springboot核心特性

springboot核心特性

作者: 奋斗的韭菜汪 | 来源:发表于2020-07-14 17:48 被阅读0次

1、条件装配@Conditional(User.class)注解使用
类实现Condition接口重写matches方法,返回boolean值,@Conditonal通过类中matches返回的boolean值决定当前bean是否加载
@ConditionalOnBean // 当给定的在bean存在时,则实例化当前Bean
@ConditionalOnMissingBean // 当给定的在bean不存在时,则实例化当前Bean
@ConditionalOnClass // 当给定的类名在类路径上存在,则实例化当前Bean
@ConditionalOnMissingClass // 当给定的类名在类路径上不存在,则实例化当前Bean

2、spring如何实现第三方组件自动装配?
ImportSelector
Registator
实现ImportSelector接口重写selectImports方法,返回所有配置类全类名,自定义注解将当前类import进注解,在springbootApplication启动入口加上注解开启注入

public class WzxDefinationImportSelector implements ImportSelector {
    //动态导入bean,告诉spring配置类的位置
    @Override
    public String[] selectImports(AnnotationMetadata annotationMetadata) {
        return new String[]{MybatisConfiguration.class.getName(), RedisTemplate.class.getName()};
    }
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(WzxDefinationImportSelector.class)
public @interface EnableConfiguration {
}

@EnableConfiguration
@SpringBootApplication
public class SpringBootDemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext ca = SpringApplication.run(SpringBootDemoApplication.class, args);
        System.out.println(ca.getBean(MybatisConfiguration.class));
        System.out.println(ca.getBean(RedisTemplate.class));
    }

}

约定优于配置:spring定义了一个规范,所有starter组件(第三方组件)都有需要一个classpath:META-INF/spring.factories文件,通过这个文件来告诉spring需要加载到spring容器的bean的位置
starter组件分为两类
1、spring官方包 spring-boot-starter-xxx(bean的动态装配发现配置在spring自己的spring-boot-autoconfigure包中,只需引入依赖就可以,不需要spring.factories文件)
2、第三方包 xxx-spring-boot-starter (需要满足以上spi机制进行bean的动态装配,也就是需要spring.factories文件)
classpath:META-INF/additional-spring-configuration-metadata.json文件:文件名称是约定写法,文件作用主要是给properties文件参数做解释作用,
源码地址:
https://github.com/WilliamEvan/my-learning/tree/master/spring-boot-demo
https://github.com/WilliamEvan/my-learning/tree/master/core-app

相关文章

网友评论

      本文标题:springboot核心特性

      本文链接:https://www.haomeiwen.com/subject/gvyxhktx.html