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,缘分让我们相遇

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

猜你喜欢

转载自juejin.im/post/7127834382248706055