前面的文章中我们讲述了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这个类~