总结:Spring Boot 之spring.factories

一、介绍

Spring IOC会将所有的对象交由Spring管理,扫描对象是在Spring boot的路径下的所有配置类注解,需要管理的对象。

但是:如果这些Bean路径不在Spring Boot的包扫描路径下,怎么办?这样不就实例化不了了吗?

有两种方式解决这个问题:

方式一:通过在启动类中加上@Import注解,以 SwaggerConfig 为例。
复制代码
@Configuration
@EnableSwagger2
public class SwaggerConfig implements EnvironmentAware {
    private static final Logger log = LoggerFactory.getLogger(SwaggerConfig.class);
    @Autowired
    private Environment env;
    @Value("${swagger.scan.package}")
    private String swaggerScanPackage;

    public SwaggerConfig() {
    }

    @Bean
    public Docket createRestApi() {
        Predicate<String> path = PathSelectors.any();
        if (Arrays.asList(this.env.getActiveProfiles()).contains("prod")) {
            path = PathSelectors.none();
        }

        return (new Docket(DocumentationType.SWAGGER_2)).apiInfo(this.apiInfo()).select().apis(RequestHandlerSelectors.basePackage(this.swaggerScanPackage)).paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return (new ApiInfoBuilder()).title("APIs").description("............").termsOfServiceUrl("https://js.dazhi.loan.com").version("1.0").build();
    }

    @Override
    public void setEnvironment(Environment environment) {

    }
}

启动类上加上@Import注解,如下:

但是有个问题,当这类配置比较多的时候,启动类会很繁琐。

方式二:使用spring.factories

采用spring.factories 的方式去加载SwaggerConfig类,在resources目录下新建一个META-INF 的目录,然后在

新建一个spring.factories 的文件,里面的内容为:

复制代码
org.springframework.boot.autoconfigure.EnableAutoConfiguration=

com.sg.config.SwaggerConfig

这样也可以加载到SwaggerConfig。

二、spring.factories加载使用

Spring boot使用SpringFactoriesLoader来加载spring.factories。

可通过Spring boot启动源码的获取监听器方法查看。

根据对下面代码的追踪可知,最终是通过读取META-INF/spring.factories读取里面的监听器类然后做响应的操作。

复制代码
SpringApplicationRunListeners listeners = getRunListeners(args);
相关推荐
欢迎来到祖安!2 小时前
企业微信 API 接口能力介绍:支持消息收发、图片发送、表情互动、联系人管理等多场景应用
java·前端·数据仓库·spring cloud·企业微信
dadaobusi6 小时前
学习:RV lkvm SBI
java·学习·spring
HEJOO98 小时前
深入理解 Java volatile 关键字:原理、用法与常见误区
java·开发语言·spring
曹牧8 小时前
Java:no content to map due to end of input
java·开发语言
阿维的博客日记8 小时前
Example 类全场景实战指南
java·mybatis
两点王爷8 小时前
SpringBoot 项目集成 GeoServer 源码,实现地图服务发布
java·spring boot·后端
Javatutouhouduan9 小时前
Java如何速通性能优化难题?
java·java面试·jvm调优·后端开发·java程序员·java八股文·java性能优化
lemon_sjdk9 小时前
DOM 节点
java·前端·javascript
leoZ2319 小时前
2026-09-09-springboot-cloud-deploy-pitfalls
java·前端·javascript·vue.js·人工智能·spring boot·后端
驭渊的小故事10 小时前
多线程02
java·开发语言·jvm