Spring boot 自动装配
在 Spring Boot 场景下,基于约定大于配置的原则,实现 Spring 组件自动装配的目的。其中使用了底层装配技术
底层装配技术
- Spring 模式注解装配
- Spring @Enable 模块装配
- Spring 条件装配装配
- Spring 工厂加载机制
- 实现类: SpringFactoriesLoader
- 配置资源: META-INF/spring.factories
实现方法
- 激活自动装配 - @EnableAutoConfiguration
- 实现自动装配 - XXXAutoConfiguration
- 配置自动装配实现 - META-INF/spring.factories
实现
- 启动类上使用@EnableAutoConfiguration激活自动装配
@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();
}
}
- 实现自动装配类AutoConfiguration,自动装配类上可以使用模式装配,模块装配,条件装配
@Configuration // Spring 模式注解装配
@EnableHelloWorld // Spring @Enable 模块装配
@ConditionalOnSystemProperty(name = "user.name", value = "MAIBENBEN") // 条件装配
public class HelloWorldAutoConfiguration {
}
- 在resource目录下创建META-INFspring.factories文件
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.imooc.diveinspringboot.configuration.HelloWorldAutoConfiguration