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

相关推荐
Qiuner34 分钟前
Spring Boot AOP (六)架构落地与最佳实践
spring boot·后端·架构
计算机毕设VX:Fegn08954 小时前
计算机毕业设计|基于springboot + vue在线考试系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
Tony Bai7 小时前
Go 的 AI 时代宣言:我们如何用“老”原则,解决“新”问题?
开发语言·人工智能·后端·golang
Overt0p8 小时前
抽奖系统(4)
java·spring boot·tomcat
用户47949283569159 小时前
性能提升 40 倍!实战 PostgreSQL FDW 解决微服务跨库查询难题
数据库·后端
计算机毕设VX:Fegn08959 小时前
计算机毕业设计|基于springboot + vue宠物医院管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
爱学习的小可爱卢10 小时前
JavaEE进阶——Spring核心设计模式深度剖析
java·spring·设计模式
Victor35610 小时前
Hibernate(9)什么是Hibernate的Transaction?
后端
Victor35610 小时前
Hibernate(10)Hibernate的查询语言(HQL)是什么?
后端