学习spring自动注入原理
直接上代码
xxxAutoConfiguration 配置类
@Configuration
@EnableConfigurationProperties(HelloProperties.class)
@ConditionalOnClass(HelloService.class)
@ConditionalOnProperty(prefix = "hello" ,value = "enabled",matchIfMissing = true)
public class HelloAutoConfiguration {
@Autowired
HelloProperties helloProperties;
@Bean
@ConditionalOnMissingBean(HelloService.class)
public HelloService helloService(){
HelloService helloService = new HelloService();
helloService.setMsg(helloProperties.getMsg());
return helloService;
}
}
xxxProperties 类
@Component
@Data
@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
private String msg;
}
编写 spring.factories 位置:resources/META-INF/下
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.atguigu.gulimall.order.ceshi.HelloAutoConfiguration
写个 service 和controller测试
@Service
@Data
public class HelloService {
private String msg;
public String sayHello(){
return "hello"+msg;
}
}
@RestController
@Slf4j
public class HelloTestController {
@Autowired
HelloService helloService;
@GetMapping("/hello")
public String helloTest(){
String s = helloService.sayHello();
System.out.println(s);
log.error("自定义自动配置:"+s);
return s;
}
}
源码
首先 @SpringBootApplication - @EnableAutoConfiguration -@Import(AutoConfigurationImportSelector.class) -
这个类 170 行
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
getBeanClassLoader());
Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
+ "are using a custom packaging, make sure that file is correct.");
return configurations;
}
// 可以看到,这里SpringFactoriesLoader.loadFactoryNames 去扫描具有这个文件的jar包 meta-inf/spring.factories 这个文件