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

相关推荐
xcl092534 分钟前
民宿预约系统开发实战:从需求分析到上线部署全流程解析
java·spring boot
梦在远山后38 分钟前
Python 中字符串常用写法
人工智能·后端
geovindu39 分钟前
python:HandWriting Recognition using paddlepaddle
开发语言·后端·python·paddlepaddle
步行cgn1 小时前
为何以继承方式引入SpringBoot
java·spring boot·后端
Mr_hou1 小时前
左手.NET右手Node:一个后端开发的双修之路
后端
wno7041 小时前
Spring Boot配合Hibernate Validator参数校验
spring boot·后端·hibernate
astronautyi2 小时前
Go 运行时内存分配与 GC 位图深度剖析
开发语言·后端·golang
techdashen2 小时前
Go 中如何处理错误
开发语言·后端·golang
GoGeekBaird2 小时前
Agent 时代,你的生产环境,真的敢让它裸奔吗
后端·agent
IT_陈寒2 小时前
Redis Pipeline用错竟比不用还慢,这个坑我帮你踩过了
前端·人工智能·后端