总结:Spring Boot 之spring.factories

一、介绍

Spring IOC会将所有的对象交由Spring管理,扫描对象是在Spring boot的路径下的所有配置类注解,需要管理的对象。

但是:如果这些Bean路径不在Spring Boot的包扫描路径下,怎么办?这样不就实例化不了了吗?

有两种方式解决这个问题:

方式一:通过在启动类中加上@Import注解,以 SwaggerConfig 为例。
复制代码
@Configuration
@EnableSwagger2
public class SwaggerConfig implements EnvironmentAware {
    private static final Logger log = LoggerFactory.getLogger(SwaggerConfig.class);
    @Autowired
    private Environment env;
    @Value("${swagger.scan.package}")
    private String swaggerScanPackage;

    public SwaggerConfig() {
    }

    @Bean
    public Docket createRestApi() {
        Predicate<String> path = PathSelectors.any();
        if (Arrays.asList(this.env.getActiveProfiles()).contains("prod")) {
            path = PathSelectors.none();
        }

        return (new Docket(DocumentationType.SWAGGER_2)).apiInfo(this.apiInfo()).select().apis(RequestHandlerSelectors.basePackage(this.swaggerScanPackage)).paths(PathSelectors.any()).build();
    }

    private ApiInfo apiInfo() {
        return (new ApiInfoBuilder()).title("APIs").description("............").termsOfServiceUrl("https://js.dazhi.loan.com").version("1.0").build();
    }

    @Override
    public void setEnvironment(Environment environment) {

    }
}

启动类上加上@Import注解,如下:

但是有个问题,当这类配置比较多的时候,启动类会很繁琐。

方式二:使用spring.factories

采用spring.factories 的方式去加载SwaggerConfig类,在resources目录下新建一个META-INF 的目录,然后在

新建一个spring.factories 的文件,里面的内容为:

复制代码
org.springframework.boot.autoconfigure.EnableAutoConfiguration=

com.sg.config.SwaggerConfig

这样也可以加载到SwaggerConfig。

二、spring.factories加载使用

Spring boot使用SpringFactoriesLoader来加载spring.factories。

可通过Spring boot启动源码的获取监听器方法查看。

根据对下面代码的追踪可知,最终是通过读取META-INF/spring.factories读取里面的监听器类然后做响应的操作。

复制代码
SpringApplicationRunListeners listeners = getRunListeners(args);
相关推荐
WeiXin_DZbishe6 小时前
基于springboot宠物领养系统-计算机毕设 附源码【课程设计】94217
vue.js·spring boot·python·django·php·课程设计
vx_bisheyuange7 小时前
基于SpringBoot的体育商品推荐系统
spring boot·毕业设计
别动我齐刘海7 小时前
C++ 工程化学习
java·linux·前端·c++·学习·机器学习·机器人
Wx-bishekaifayuan7 小时前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
人工智能·spring boot·后端·python·课程设计·express·旅游
Wx-bishekaifayuan8 小时前
springboot汉中旅游服务平台41442-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
code2cat8 小时前
Java进阶篇之AtomicLongFieldUpdater:把累计额度留在对象字段中
java·cas·并发编程
WeiXin_DZbishe8 小时前
基于springboot城市公交实时运营与调度系统-计算机毕设 附源码【课程设计】66173
java·vue.js·spring boot·后端·python·php·课程设计
泡茶喝茶写代码8 小时前
A股量化数据工程:从 REST 接口到策略信号(第 18 篇):放量缩量异动扫描
java·python·股票数据api·股票数据api接口·股票api数据接口·股票量化数据api·股票量化数据接口
WeiXin_DZbishe9 小时前
基于Springboot+AI的kuall音乐广场的设计与实现-计算机毕设 附源码【课程设计】12715
vue.js·人工智能·spring boot·后端·python·php·课程设计