Spring Boot的优势在于内置大量习惯性的配置,便于与第三方集成,即“习惯优于配置”,让项目能够快速运行起来,下面我们就探究下Spring Boot自动集成配置的原理。
Spring Boot关于自动配置的jar包位于spring-boot-autoconfigure-*.jar中,
spring boot的启动类中通常使用组合注解@SpringBootApplication,其中最主要的就是@EnableAutoConfiguration,查看该注解的源码:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = “spring.boot.enableautoconfiguration”;
Class>[] exclude() default {};
String[] excludeName() default {};
}
它通过@Import注解获得AutoConfigurationImportSelector类,该类通过调用SpringFactoriesLoader.loadFactoryNames方法将spring-boot-autoconfigure-*.jar jar包下META-INF/spring.factories的配置项加载入容器,这样我们就可以读取application.properties中的配置项了。
下面我们以一个实例来说明spring boot自动配置项:
1. 首先添加需要配置的服务:
public class HelloService {
private String msg;
public String sayHello(){
return "hello "+msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
2. 服务对应属性类:
//读取配置文件前缀为hello.msg的配置
@ConfigurationProperties(prefix = “hello”)
public class HelloServiceProperties {
//默认配置hello.msg=wold
public static final String MSG=“wold”;
private String msg=MSG;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
3. 自动配置类
/**
@author whp 18-8-14
*/
@Configuration
//允许属性配置类
@EnableConfigurationProperties(HelloServiceProperties.class)
//属性类作用的服务类
@ConditionalOnClass(HelloService.class)
//value–数组,获取对应property名称的值,与name不可同时使用。
// 作用:value单独使用时:当对应property名称的值为false时,该configuration不生效;
// 当对应property名称的值为除false之外的值时,该configuration生效
//缺少该property时是否可以加载。如果为true,没有该property也会正常加载;反之报错
@ConditionalOnProperty(prefix = “hello”,value=“enable”,matchIfMissing = true)
public class HelloServiceAutoConfiguration {
@Autowired
private HelloServiceProperties helloServiceProperties;
@Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService(){
HelloService helloService=new HelloService();
helloService.setMsg(helloServiceProperties.getMsg());
return helloService;
}
}
4. 简单使用
@RestController
@SpringBootApplication
public class WhpDemoApplication {
@Autowired
private BookConfig bookConfig;
@Autowired
private HelloService helloService;
@RequestMapping(value = "/",method = RequestMethod.GET)
public String index(){
return "book is write by "+ bookConfig.getTime();
}
@RequestMapping(value = "/sayHello",method = RequestMethod.GET)
public String sayHello(){
return helloService.sayHello();
}
public static void main(String[] args) {
SpringApplication application=new SpringApplication(WhpDemoApplication.class);
application.run(args);
}
}
当配置文件中配置hello.msg=whp属性时,则输出:
【总结】
spring boot运行原理就是容器的思想,先将普遍使用的配置项加载入容器,只有在加载相应jar包的情况下,才能将配置属性通过配置文件加载入服务类。
参考书籍:《JavaEE开发者的颠覆:Spring boot实战》
作者:king_eagle2015
来源:CSDN
原文:https://blog.csdn.net/whp15369657805/article/details/81669192
版权声明:本文为博主原创文章,转载请附上博文链接!