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完全废除这种方式

相关推荐
字节渡客9 小时前
Redis键明明过期了,业务还在读到旧数据
数据库·redis·spring
To_OC9 小时前
从一头雾水到跑通全流程:我用一个周末啃透了JWT登录鉴权
前端·后端·http
我可能是个假开发10 小时前
FTP Unicode 文件名导致 `550` 的问题分析与解决方案
java·开发语言·spring
前端兰博10 小时前
05-Redis
redis·后端
databook11 小时前
从手动检查到自动监控:一个数据质量工作流的实现
后端·python·数据分析
【JAVA】玩家11 小时前
Spring核心原理全解析:从零到生产实战
java·后端·spring
东风破_11 小时前
从 Neo4j 到 GraphRAG:用 Text-to-Cypher 构建图检索 RAG
人工智能·后端
llqbzllll13 小时前
Spring AI 工具调用不是反射一下就结束:用 2.0.1 跑通失败恢复与调用上限
人工智能·后端
狼爷14 小时前
Rust/Go/Java/Python/PHP 大比拼:负载下后端框架到底差多少?
java·后端·编程语言
mantou13215 小时前
我给 AI Agent 做了个「油猴」:让 Claude Code / Codex 直接用你已登录的浏览器
前端·javascript·后端