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 分钟前
Netty 4.2.x 源码深度解析 (二十四):池化内存分配 —— PoolArena、PoolChunk 与 PoolSubpage
java·后端·架构
ServBay1 小时前
PHP 8.6 最新发布:语法更新、实用函数与升级要点
后端·php
我不会起名字3221 小时前
Agent 总调错工具?MCP 接进 Go 后端的 4 个约束
后端·go·agent·mcp
考虑考虑1 小时前
git刷新远程分支列表
git·后端·gitlab
雪芽蓝域zzs1 小时前
第 10 章:Maven 打包
spring boot
十有八七2 小时前
手搓 Agent(四):长点记性——上下文满了怎么办,怎么记住上一次
前端·人工智能·后端
杨凯凡2 小时前
Spring Framework 7 原生重试与并发限制实战:@Retryable、@ConcurrencyLimit 能替代 Resilience4j 吗?
数据库·spring·sqlserver
王晋1572 小时前
第一次使用银河麒麟:从 Windows 迁移到国产 Linux 桌面的入门指南
后端
用户46043852250863 小时前
关于 Paimon-Rust 的写操作(细节)
后端