@ConfigurationPropertiesScan
注解是 Spring Boot 2.2 版本引入的一个注解,它用于自动扫描并注册带有 @ConfigurationProperties
注解的类为 Spring Bean。
@ConfigurationPropertiesScan
注解会在类路径中扫描 @ConfigurationProperties
注解,并将它们注册为 Spring Bean。这样,在应用程序中就可以使用 @Autowired
或 @Inject
注解来自动注入这些配置属性类,而不需要手动声明并配置一个对应的 Bean。
一般情况下,@ConfigurationProperties
注解用于将配置文件中的属性值绑定到 Java 类的字段上。例如:
@ConfigurationProperties(prefix = "myapp")
public class MyAppConfig {
private String name;
private int age;
// getters and setters
}
配置文件:
myapp.name=WeTab AI
myapp.age=3
通过 @ConfigurationPropertiesScan
注解,可以在 Spring Boot 应用中自动扫描并注册 MyAppConfig
作为一个 Bean,然后在其他组件中使用 @Autowired
注解进行注入。
使用示例:
@Configuration
@ConfigurationPropertiesScan
public class AppConfigConfiguration {
// ...
}
@Service
public class MyService {
@Autowired
private MyAppConfig appConfig;
// ...
}
在上面的代码中,MyService
类中的 appConfig
字段将会被自动注入为 MyAppConfig
类的实例,而不需要显式地声明一个 @Bean
方法来配置它。
需要注意的是,@ConfigurationPropertiesScan
注解需要与 @Configuration
注解一起使用,因为它的作用是扫描并注册配置类。而 @Configuration
注解则用于标记类为配置类,表明它是一个 Spring Bean 配置的源头。
同时,还需要注意的是,@ConfigurationPropertiesScan
注解只会扫描和注册带有 @ConfigurationProperties
注解的类,如果你使用了其他注解如 @Component
、@Service
等,需要一起使用,或者使用 @ComponentScan
注解进行包扫描。