无法使Spring的ImportAware工作

vltsax25  于 2024-01-05  发布在  Spring
关注(0)|答案(1)|浏览(119)

我试图创建自己的@ EnableXXX风格的annotation(即@EnableCustomizedPropertySources)。为此,annotation导入CustomizedPropertySourcesConfiguration类,后者又实现了ImportAware,以便访问@EnableCustomizedPropertySources annotation的属性。
注解:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Import(CustomizedPropertySourcesConfiguration.class)
  4. public @interface EnableCustomizedPropertySources {
  5. String externalFolderName();
  6. String propertiesFileName();
  7. (...)
  8. }

字符串
导入的配置类:

  1. @Configuration
  2. public class CustomizedPropertySourcesConfiguration implements ImportAware {
  3. protected AnnotationAttributes enableCustomizedPropertySourcesAttributes;
  4. @Override
  5. public void setImportMetadata(AnnotationMetadata importMetadata) {
  6. Map<String, Object> attributes = importMetadata.getAnnotationAttributes(EnableCustomizedPropertySources.class.getName(), false);
  7. this.enableCustomizedPropertySourcesAttributes = AnnotationAttributes.fromMap(attributes);
  8. }
  9. @Bean
  10. public PropertySourcesPlaceholderConfigurer propertySource() {
  11. return (...);
  12. }
  13. }


问题是,当我用@EnableCustomizedPropertySources annotation注解一些@Configuration class时,Spring不会调用setImportMetadata方法,因此我无法访问annotations属性。

xxslljrj

xxslljrj1#

ImportAware类(CustomizedPropertySourcesConfiguration)需要以下两个:

  1. @Configuration
  2. @Component

字符串

相关问题