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