学习spring自动注入原理

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

学习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 这个文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值