原因

为什么要使用,因为在程序开发中,可能包名不一样,pom依赖的很多的jar 他们是如何把这些类进行注入到spring容器中的呢。
所以springboot就提出了spring.factories

使用

一、第一种

新建一个Test类

  1. package com.test;
  2. public class Test {
  3. public Test() {
  4. System.out.println("Test加载");
  5. }
  6. }

1.看下图
如果我们要把Test这个类注入到IOC中,原来的方式只能写到启动类的包下面
image.png
2.,使用spring.factories 可以解决这个问题,在resources下面创建文件夹META-INF 在创建一个文件spring.factories
image.png
3.编辑 spring.factories 文件,写入

  1. # Auto Configure
  2. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  3. com.test.Test

4.启动,在控制台我们可以看到,说明这个类以及注入到spring中
image.png
原理
SpringFactoriesLoader载荷从和实例化给定类型的工厂“META-INF / spring.factories”文件,其可存在于在类路径多个JAR文件。 该spring.factories文件必须为Properties格式,其中的关键是接口或抽象类的完全合格的名称和值是一个逗号分隔的实现类名的列表。 例如:
example.MyService=example.MyServiceImpl1,example.MyServiceImpl2
其中example.MyService是接口的名称,和MyServiceImpl1和MyServiceImpl2两种实现。

二、第二种
在@SpringBootApplication启动类加上@Import(需要注入的类)

版权声明:本文为CSDN博主「我俗人」的原创文章。
原文链接:https://blog.csdn.net/qq_32448349/article/details/109155988