SpringBoot学习笔记---自动装配续3之SpringBoot的自动装配

前面的文章中我们讲述了SpringFramework的一些装配方式,SpringFrameWork需要开发人员手动配置,虽然有Enable简化了操作。但是它没有办法实现0配置。

SpringBoot自动装配基于约定大于配置的原则,实现Spring组件自动装配的目的。

SpringBoot的装配方式有:模式注解、@Enable模块、条件装配、工厂加载机制

装配的实现有3个步骤:

1.激活自动装配

2.实现自动装配

3.配置自动装配实现。

我们前面很大的篇幅讲了模式注解、@Enable模块、条件装配,就是为了给SpringBoot的自动装配做准备,OK,进入正题,我们自己来手动的实现以下SpringBoot的自动装配就会明白其中的道理了。

先激活自动装配

如何激活呢?我们在引导类中进行激活:

@EnableAutoConfiguration
public class EnableAutoConfigurationBootstrap {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableAutoConfigurationBootstrap.class)
                .web(WebApplicationType.NONE)
                .run(args);

        // helloWorld Bean 是否存在
        String helloWorld =
                context.getBean("helloWorld", String.class);

        System.out.println("helloWorld Bean : " + helloWorld);

        // 关闭上下文
        context.close();

    }
}

@EnableAutoConfiguration表示就是激活自动装配,这个是SpringBoot中的注解,有了它表示就可以使用自动装配了。

实现一个自动装配:

@Configuration // Spring 模式注解装配
@EnableHelloWorld // Spring @Enable 模块装配
@ConditionalOnSystemProperty(name = "user.name", value = "天帝") // 条件装配
public class HelloWorldAutoConfiguration {
}

我们的自动装配实现,3中装配模式都综合运用进来了,先看看@EnableHelloWorld

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(HelloWorldImportSelector.class)
public @interface EnableHelloWorld {
}

在看看HelloWorldImportSelector和其中的HelloWorldConfiguration:

public class HelloWorldImportSelector implements ImportSelector {
    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
    	System.out.println("selectTOr判断逻辑以及返回HelloWorldConfiguration");
        return new String[]{HelloWorldConfiguration.class.getName()};
    }
}

 

public class HelloWorldConfiguration {

    @Bean
    public String helloWorld() { // 方法名即 Bean 名称
        return "Hello,World 2018";
    }

}

 条件注解和上一篇文章的一样,这里就不再赘述了,有兴趣的去翻看一下上篇文章。

配置自动装配的实现:

在resources目录下简历一个META-INF目录,然后命名一个spring.factories文件:

其内容如下,就是我们在步骤2中实现的一个自动装配:

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.imooc.diveinspringboot.configuration.HelloWorldAutoConfiguration

为什么3个步骤完成后直接运行就能成功呢?这是因为SpringBoot会使用工厂加载机制,读取步骤3中的spring.factories,找到其中的实现类,然后根据相关条件装配Bean,这样整个自动装配就完成了。是不是很简单呢?SpringBoot的自动装配原理就讲到这里。下来的文章我们将好好剖析一下SpringApplication这个类~

  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值