SpringBoot之spring.factories的用法(16)

原因

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

所以springboot就提出了spring.factories

使用

一、第一种

新建一个Test类

package com.test;
 
 
public class Test {
    public Test() {
        System.out.println("Test加载");
    }
} 

1.如果我们要把Test这个类注入到IOC中,原来的方式只能写到启动类的包下面,或者在启动类中加@ComponentScan,里面是包名。

2.,使用spring.factories 可以解决这个问题,在resources下面创建文件夹META-INF 在创建一个文件spring.factories。

3.编辑 spring.factories 文件,写入

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
 com.test.Test

4.启动,在控制台我们可以看到,说明这个类以及注入到spring中。

原理

SpringFactoriesLoader载荷从和实例化给定类型的工厂“META-INF / spring.factories”文件,其可存在于在类路径多个JAR文件。 该spring.factories文件必须为Properties格式,其中的关键是接口或抽象类的完全合格的名称和值是一个逗号分隔的实现类名的列表。 例如:
example.MyService=example.MyServiceImpl1,example.MyServiceImpl2
其中example.MyService是接口的名称,和MyServiceImpl1和MyServiceImpl2两种实现。

二、第二种

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

原文地址:https://www.cnblogs.com/h-z-y/p/14604913.html