本文将介绍spring.factories的用法已经它与@ComponentScan之间有什么联系和区别
问题引出
在编写项目中,其中一个模块heima-leadnews-common中有一个异常处理类ExceptionCatch:
ExceptionCatch内容:
package com.heima.common.exception;
import ...
@ControllerAdvice //控制器增强类
@Slf4j
public class ExceptionCatch {
/**
* 处理不可控异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseResult exception(Exception e){
e.printStackTrace();
log.error("catch exception:{}",e.getMessage());
System.out.println("异常捕获类,启动!");
return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
}
/**
* 处理可控异常 自定义异常
* @param e
* @return
*/
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseResult exception(CustomException e){
log.error("catch exception:{}",e);
return ResponseResult.errorResult(e.getAppHttpCodeEnum());
}
}
在这个模块中发现有一个文件:spring.factories,
其内容是:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.heima.common.exception.ExceptionCatch,\
com.heima.common.swagger.SwaggerConfiguration,\
com.heima.common.swagger.Swagger2Configuration
这个文件是干什么用的?
答:spring.factories将各种自动配置类与对应的配置类集中在一起,方便Spring Boot自动装配。在Spring Boot启动时,它会扫描classpath下所有的spring.factories文件,加载其中的自动配置类,并将它们注入到Spring ApplicationContext中,使得项目能够自动运行。
这时候会问:使用@Configuration或者@Component等类似注解注释的类不是会在项目启动的时候自动创建吗,为什么要使用spring.factories?
首先了解@Component和@ComponentScan注解
当我们点进项目的启动类@SpringBootApplication注解中:
发现@SpringBootApplication注解里由多个注解组成,其中包括@ComponentScan注解,所以@SpringBootApplication注解也有@ComponentScan的作用。当项目启动后,@ComponentScan会扫描当前启动类所在路径下包中的组件,比如在heima-leadnews-user模块中:
UserApplication在启动时就会扫描com.heima.user下所有被@Component或类似注解注释的组件并将其注册到Spring容器中。
但是在这个项目中,异常处理类与我们要启动的启动类是在不同的模块下,所以UserApplication的@ComponentScan扫描不到异常处理类,我们就需要使用spring.factories。
不过只使用@ComponentScan也可以实现不同模块下组件的注册,我们只需要在UserApplication启动类中加上注解@ComponentScan(value={“com.heima.common”,“com.heima.user”}):
@SpringBootApplication
@ComponentScan(value={"com.heima.common","com.heima.user"}) //com.heima.common是异常处理类所在包路径
@EnableDiscoveryClient
@MapperScan("com.heima.user.mapper")
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class,args);
}
}
注意:
- 不能只写@ComponentScan(“com.heima.common”),加上@ComponentScan后UserApplication启动类@SpringBootApplication注解中的@ComponentScan就失效了,导致启动类所在包的组件无法被扫描注册,所以需要两个包都被扫描;
- 将heima-leadnews-common和heima-leadnews-service需要注册到一个pom中:
<modules>
<module>heima-leadnews-common</module>
<module>heima-leadnews-utils</module>
<module>heima-leadnews-model</module>
<module>heima-leadnews-feign-api</module>
<module>heima-leadnews-service</module>
<module>heima-leadnews-gateway</module>
<module>heima-leadnews-test</module>
</modules>
以上就是spring.factories和@ComponentScan讲解。