Spring Boot 中的 @ComponentScan
和 @EnableAutoConfiguration
注解有什么区别?有必要添加这些吗?没有这些注释,我的应用程序运行良好。我只是想了解为什么我们必须添加它们。
最佳答案
What is the difference between the @ComponentScan and @EnableAutoConfiguration annotations in Spring Boot?
@EnableAutoConfiguration
注释告诉 Spring Boot 根据您添加的 jar 依赖项“猜测”您将如何配置 Spring。例如,如果 HSQLDB 在您的类路径中,并且您没有手动配置任何数据库连接 bean,那么 Spring 将自动配置内存数据库。
@ComponentScan
告诉 Spring 在指定的包中查找其他组件、配置和服务。 Spring 能够从预定义的项目包中自动扫描、检测和注册您的 bean 或组件。如果未指定包,则将当前类包作为根包。
Is it necessary to add these?
如果您需要 Spring Boot 自动为您配置所有内容 @EnableAutoConfiguration
是必须的。你不需要手动添加,spring会根据你提供的注解在内部为你添加。
其实是@SpringBootApplication
注解等价于使用 @Configuration
, @EnableAutoConfiguration
和 @ComponentScan
使用它们的默认属性。
另请参阅:
关于java - Spring Boot 中的 @ComponentScan 和 @EnableAutoConfiguration 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35005158/