ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-01-21 13:01:54  阅读:199  来源: 互联网

标签:装配 star Springboot boot hello 源码 自动 public 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,缘分让我们相遇

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

标签:装配,star,Springboot,boot,hello,源码,自动,public,starter
来源: https://blog.csdn.net/qq_35551875/article/details/122407420

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有