spring.factories使用

前言

在Springboot开发中,除了使用@Configuration@Bean@Compont等注解注入Bean,还可以使用spring.factories配置文件注入Bean

spring.factories使用

spring.factories是一般在编写spring Starter时,经常使用Bean注入的一种配置形式,原理是springboot在启动的时候,会去扫描每个包下面的这个配置文件,从而注入Bean

spring.factories配置

创建一个Springboot在3.0以下的版本,然后新建一个类

typescript 复制代码
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class UserService {

    public String say() {
        log.info("===================say()方法被调用===================");
        return "success";
    }
}

然后在resources文件夹下新建一个目录

复制代码
META-INF

具体如下

文件内容为

ini 复制代码
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
  org.example.demohello.service.UserService

其中org.example.demohello.service.UserService是BeanUserService的文件路径,这种项目在启动的时候,就会注入UserService

总结

Springboot3.0版本以下可以使用这种方式注入Bean,但是从Springboot2.7版本之后,就不再推荐这种形式注入Bean了,Springboot2.7版本还可以兼容,Springboot3.0完全废除这种方式

相关推荐
凤山老林16 小时前
Spring Boot 3.x AOT 编译实战:从原理、踩坑到生产落地
java·spring boot·后端
博傅16 小时前
Spring 核心原理
java·后端·spring
用户9385156350716 小时前
掘金风格后端数据库设计实战:从用户表到分布式架构,一文搞定
后端·sql
玹外之音17 小时前
Spring AI + Elasticsearch 向量存储实战:从零构建智能文档检索系统
人工智能·spring·elasticsearch
拾光师17 小时前
Hadoop 三种运行模式:从单机调试到生产集群,一路搭过来
后端
摇滚侠17 小时前
《SpringBoot 3:入门与应用实战》第 5 章 使用 Spring Boot 阅读笔记 9
java·spring boot·笔记
进阶的小名17 小时前
Spring AI 2.0 探索:多 OpenAI-Compatible 模型接入,以及下一代 Session 记忆管理
java·人工智能·后端·gpt·spring·ai·chatgpt
卷无止境17 小时前
FastAPI 的 Metadata 到底是什么,又牵动了哪些核心概念
后端·python
卷无止境17 小时前
FastAPI 调试实战,从断点到生产环境的排错心法
后端·python
敢敢のwings18 小时前
智元 GO-2 与 AgiBot-World 深度解读
开发语言·后端·golang