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

相关推荐
didiplus6 小时前
Python 入门第一课:为什么选择 Python?3 分钟搭建你的第一个程序
后端
dreamxian6 小时前
苍穹外卖day11
java·spring boot·后端·spring·mybatis
华科易迅7 小时前
Spring装配对象方法-注解
java·后端·spring
AwesomeDevin8 小时前
AI时代,我们的任务不应沉溺于与 AI 聊天,🤔 从“对话式编程”迈向“数字软件工厂”
前端·后端·架构
庄周的大鱼8 小时前
分析@TransactionalEventListener注解失效
java·spring·springboot·事务监听器·spring 事件机制·事务注解失效解决
Victor3568 小时前
MongoDB(60)如何使用explain命令?
后端
云烟成雨TD8 小时前
Spring AI Alibaba 1.x 系列【4】ReAct 范式与 ReactAgent 核心设计
java·人工智能·spring
Victor3568 小时前
MongoDB(59)如何分析查询性能?
后端
怒放吧德德11 小时前
Spring Boot实战:InfluxDB 2.x简单教程
java·spring boot·后端