Springboot源码分析第三弹 - 自动装配扩展,手动实现一个starter

Springboot源码分析第三弹 - 自动装配扩展,手动实现一个starter

原理回顾

经过前面的两篇文章,应该是能清楚的指定自动装配和自动配置是怎么实现的了。
今天再来回顾一下,然后我们自己实现一下

//AutoConfigurationImportSelector类
//通过classLoader获取指定key需要自动装配的类
List<String> configurations = 
//getSpringFactoriesLoaderFactoryClass return EnableAutoConfiguration.class;
//这里的key也就是自动装配EnableAutoConfiguration类路径
SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),getBeanClassLoader());

也就是说在容器的回调中,处理需要自动装配的类,在META-INF/spring.factories文件中找到key为EnableAutoConfiguration全路径名的值即可以实现自动装配。

自己实现一个star

pom.xml

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.5.6</version>
</parent>

<dependencies>
	//自动装配的类 和接口访问需要
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
</dependencies>

1. star-test-2

  • 类似与core包的结构,准备两个service
//返回时间
public class HelloService {
    public Long hello() {
        return new Date().getTime();
    }
}
//返回字符串
public class Hello1Service {
    public String hello(String name) {
        return "hello " + name;
    }
}
  • resources目录下准备META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.start.test2.service.HelloService,\
com.start.test2.service.Hello1Service

然后将build打包,保证打包能够成功!

2. star-test-1

  • pom.xml 需要引入star-test-2 jar包
<dependency>
	<groupId>com.springboot.star</groupId>
	<artifactId>star-test-2</artifactId>
	<version>1.0</version>
</dependency>
  • 准备一个controller接口类
@RestController
public class StarController {
	//采用注解的方式使用star-test-2的类
    @Autowired
    HelloService helloService;
    @Autowired
    Hello1Service hello1Service;

    @GetMapping("/hello")
    public void hello() {
        System.out.println(helloService.hello());
        System.out.println(hello1Service.hello("张三"));
    }
}
  • 启动项目,调用http://127.0.0.1:8080/hello查看输出
1642665191858
hello 张三

就这里就实现一个公用的star了,大家伙可以自己尝试一下。

到这里整个springboot体系就完结了,接下来开始mybatis章节了,喜欢的可以双击关注一下!

以上就是本章的全部内容了。

上一篇:Springboot源码分析第二弹 - 自动配置实现
下一篇:mybatis第一话 - mybatis,缘分让我们相遇

勿以恶小而为之,勿以善小而不为

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值