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

相关推荐
小码哥_常7 小时前
Spring Boot 牵手Spring AI,玩转DeepSeek大模型
后端
0xDevNull7 小时前
Java反射机制深度解析:从原理到实战
java·开发语言·后端
华洛8 小时前
我用AI做了一个48秒的真人精品漫剧,不难也不贵
前端·javascript·后端
AugustRed8 小时前
基于现有的 Controller 接口 API 暴露 MCP
spring·mcp
WZTTMoon8 小时前
Spring Boot 中Servlet、Filter、Listener 四种注册方式全解析
spring boot·后端·servlet
standovon8 小时前
Spring Boot整合Redisson的两种方式
java·spring boot·后端
Cosolar9 小时前
LlamaIndex RAG 本地部署+API服务,快速搭建一个知识库检索助手
后端·openai·ai编程
MX_93599 小时前
SpringMVC请求参数
java·后端·spring·servlet·apache
zs宝来了9 小时前
Spring Boot 自动配置原理:@EnableAutoConfiguration 的魔法
spring boot·自动配置·源码解析·enableautoconfiguration
忆想不到的晖10 小时前
Codex 探索:别急着调 Prompt,先把工作流收住
后端·agent·ai编程