昨天学习了Spring框架的手动装配,今天来看下SpringBoot
的自动化装配。
定义:基于约定大于配置的原则,实现Spring组件自动装配的目的
底层装配技术:
- Spring模式注解装配
- Spring
@Enable
模块装配
- Spring条件装配
- Spring工厂加载机制
- 实现类:
SpringFactoriesLoader
- 配置资源:
META-INF/spring.factories
实现方式:
自定义自动装配
- 激活自动装配
在昨天的工程中的bootstrap
包中新建一个EnableAutoConfigurationBootstrap
类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package cn.myjdemo.springbootlearning.bootstrap;
import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext;
@EnableAutoConfiguration public class EnableAutoConfigurationBootstrap {
public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableAutoConfigurationBootstrap.class) .web(WebApplicationType.NONE) .run(args);
context.close(); } }
|
- 实现自动装配
在configuration
包中新建一个HelloWorldAutoConfiguration
类
1 2 3 4 5 6 7 8 9 10 11 12
| package cn.myjdemo.springbootlearning.configuration;
import cn.myjdemo.springbootlearning.annotation.EnableHelloWorld; import cn.myjdemo.springbootlearning.condition.ConditionalOnSystemProperty; import org.springframework.context.annotation.Configuration;
@Configuration @EnableHelloWorld @ConditionalOnSystemProperty(name = "user.name",value = "Administrator") public class HelloWorldAutoConfiguration {
}
|
- 条件判断:
user.name == "Administrator"
- 模式注解:
@Configuration
- @Enable 模块:
@EnableHelloWorld
-> HelloWorldImportSelector
-> HelloWorldConfiguration
- > helloWorld
- 配置自动装配实现
在项目的resources
目录下新建一个文件夹META-INF
,在里面新建一个spring.factories
文件
1 2 3
| # 自动装配 org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ cn.myjdemo.springbootlearning.configuration.HelloWorldAutoConfiguration
|
然后在EnableAutoConfigurationBootstrap
检验helloWorld
Bean是否加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| package cn.myjdemo.springbootlearning.bootstrap;
import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ConfigurableApplicationContext;
@EnableAutoConfiguration public class EnableAutoConfigurationBootstrap {
public static void main(String[] args) { ConfigurableApplicationContext context = new SpringApplicationBuilder(EnableAutoConfigurationBootstrap.class) .web(WebApplicationType.NONE) .run(args);
String helloWorld = context.getBean("helloWorld",String.class);
System.out.println(helloWorld);
context.close(); } }
|
运行后发现helloWorld加载成功
因此可以看出SpringBoot自动装配是在Spring框架的手动装配基础上发展而来的