学习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 这个文件
本文详细解析了Spring自动注入的实现过程,通过一个具体的HelloAutoConfiguration配置类和HelloProperties属性类来展示。在启动时,Spring通过扫描META-INF/spring.factories文件加载配置,并根据条件注解决定哪些bean被创建和注入。在测试用例中,展示了如何使用@Service和@RestController创建并测试自动配置的bean。
1150

被折叠的 条评论
为什么被折叠?



