学习spring自动注入原理

学习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 这个文件
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值