@EnableAutoConfiguration 這個注解的作用是:
從classpath中搜索所有META-INF/spring.factories配置文件然后,將其中org.springframework.boot.autoconfigure.EnableAutoConfiguration key對應的配置項加載到spring容器
下面介紹一下這個標簽的用法,這個標簽是 包含在 SpringBootApplication 這個注解中的。
@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan( excludeFilters = {@Filter( type = FilterType.CUSTOM, classes = {TypeExcludeFilter.class} ), @Filter( type = FilterType.CUSTOM, classes = {AutoConfigurationExcludeFilter.class} )} ) public @interface SpringBootApplication {
1.首先 我們定一個 Demo類。
package com.example.demo; public class Demo { public String hello(){ return ("hello world"); } }
2.定義一個配置類。
package com.example.demo; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnJava; import org.springframework.boot.system.JavaVersion; import org.springframework.context.annotation.Bean; //@ConditionalOnBean(name = "operaSinger1") //@ConditionalOnJava(range = ConditionalOnJava.Range.EQUAL_OR_NEWER,value = JavaVersion.EIGHT) public class DemoAutoConfigure1 { @Bean private Demo demo(){ return new Demo(); } }
這里我們產生一個Demo類的實例,並注入到容器中,一般這個類的名字使用AutoConfigure 結束,試驗過其實也不一定。
3.配置到 spring.factories 文件中。
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.demo.DemoAutoConfigure1
4.在代碼中使用Demo實例。
@RestController public class DemoController { @Autowired private Demo demo; @GetMapping("/demo") public String demo(){ return demo.hello(); } }
如果正常 這個實例是可用的。
我們也可以在這個配置類上增加一些條件注解比如:
@ConditionalOnJava(range = ConditionalOnJava.Range.EQUAL_OR_NEWER,value = JavaVersion.NINE)
比如比如使用java的版本,我當前使用的是java8 ,執行后拋出錯誤如下:
The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true) The following candidates were found but could not be injected: - Bean method 'demo' in 'DemoAutoConfigure1' not loaded because @ConditionalOnJava (9 or newer) found 1.8
