✅ 一、@ComponentScan("com.ylt")
🔍 作用:
用于告诉 Spring 容器去扫描并注册 Spring Bean,比如:
@Component
@Service
@Repository
@Controller
@RestController
- 自定义注解(如果有定义)
🧠 示例:
@ComponentScan("com.ylt")
@Configuration
public class AppConfig {
}
📌 适用对象:
- 所有被 Spring 注解标注的类(如
RedisCache
)
📦 作用范围:
扫描 com.ylt
包及其子包下所有被标注为组件的类,并将它们注册为 Spring 容器中的 Bean。
✅ 二、@ConfigurationPropertiesScan("com.ylt.framework.common.config")
🔍 作用:
用于扫描并注册带有 @ConfigurationProperties
注解的类,这些类通常用于绑定配置文件(如 application.yml
)中的属性。
🧠 示例:
@ConfigurationProperties(prefix = "my.config")
public class MyConfigProperties {
private String name;
private int timeout;
// getter/setter
}
然后你通过 @ConfigurationPropertiesScan
告诉 Spring 去哪里找这些类:
@ConfigurationPropertiesScan("com.ylt.framework.common.config")
public class AppConfig {
}
📌 适用对象:
- 所有使用
@ConfigurationProperties
的类
📦 作用范围:
只扫描 com.ylt.framework.common.config
包及其子包中使用 @ConfigurationProperties
注解的类,并注册为 Spring Bean。
✅ 三、总结对比
@ComponentScan
是用来扫描 Spring Bean 的,@ConfigurationPropertiesScan
是专门用来扫描配置属性类的,它们解决的是不同类别的问题,通常需要一起使用,尤其是在你有自定义配置类的情况下。