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

相关推荐
明月_清风1 天前
Pi Agent 深度解析:开源极简终端 AI 编码代理的终极指南
前端·后端·ai编程
程序员cxuan1 天前
DeepSeek Harness 必装的插件公布了!
人工智能·后端·程序员
fatcoder1 天前
玩转Nginx 03 — location 匹配规则:让不同的路径各回各家
前端·后端·nginx
wno7041 天前
Spring Boot JdbcTemplate配置Druid多数据源
java·spring boot·后端
月才1 天前
Spring Boot 接口参数校验从入门到精通
后端
码农大叔的博客1 天前
golang示例:switch
开发语言·后端·golang
Zane19941 天前
多开几个线程,为什么算数字反而没变快?一文讲透 CPython 的 GIL
后端·python
wear工程师1 天前
Spring Boot 服务挂了却没重启?先分清 systemd 的三次判断
spring boot
一只叫煤球的猫1 天前
Spring AI 2.0 源码解析(二):Starter 如何自动装配 ChatClient ?
后端·面试·langchain
聊浮游1 天前
JAVA2026最新全套学习资料、学习路线
java·开发语言·jvm·mysql·spring·maven·idea