我正在尝试为Spring框架编写自己的@Enable
批注,该批注应如下使用:
package com.example.package.app;
@SpringBootApplication
@com.example.annotations.EnableCustom("com.example.package.custom")
public class MyApplication {}
我关注了Component scan using custom annotation,但这带来了一些限制:
我无法使基本包属性动态化,即无法传递"com.example.package.base"
,但需要在配置中预定义包。
我看过@AliasFor
,但无法正常工作。
当我忽略基本包时,扫描从注释的定义包开始,而不是从带注释的类的包开始。在上面的示例中,它只会为com.example.annotations
中的类扫描并创建bean,而不会为com.example.package.*
进行扫描。
我看了在EntityScanPackages.Registrar.class
注释中导入的@EntityScan
,但这是一个内部类,我的注释无法导入。
如果我将@ComponentScan(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = MyAnnotation.class))
放在MyApplication
类上,则一切正常,但是当将其移到@EnableCustom
的元注释时,一切停止。如何告诉Spring Framework将@EnableCustom
考虑为以某些默认值指定@ComponentScan
的另一种方式。我尝试使用@Configuration
,@Component
和其他注释进行元注释,但无济于事:
@Configuration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@ComponentScan(
includeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
value = ApplicationService.class))
public @interface EnableApplicationServices {
@AliasFor(annotation = ComponentScan.class, attribute = "basePackages")
String[] value() default {};
}
我在哪里可以找到有关此文档的信息,或者您建议从哪个起点入手?我的长期目标是要有一个Spring Boot启动器,该启动器可以供许多项目使用。
在以下存储库中可以找到M(N)WE:https://github.com/knittl/stackoverflow/tree/spring-enable-annotation
以下是包装结构的简要介绍:
// com.example.annotations.EnableCustom.java
@Configuration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
// this annotation is never honored:
@ComponentScan(
includeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
value = MyAnnotation.class))
//@Import(EnableCustom.EnableCustomConfiguration.class)
public @interface EnableCustom {
// this annotation works in combination with @Import, but scans the wrong packages.
@ComponentScan(
includeFilters = @ComponentScan.Filter(
type = FilterType.ANNOTATION,
value = MyAnnotation.class))
class EnableCustomConfiguration {}
}
// file:com.example.app.Application.java
@SpringBootApplication
@EnableCustom("com.example.app.custom.services")
// @ComponentScan(
// includeFilters = @ComponentScan.Filter(
// type = FilterType.ANNOTATION,
// value = MyAnnotation.class)) // <- this would work, but I want to move it to a custom annotation
public class Application {
}
// file:com.example.app.custom.services.MyService
@MyAnnotation
public class MyService {
public MyService() {
System.out.println("Look, I'm a bean now!");
}
}
// file:com.example.annotations.services.WrongService.java
@MyAnnotation
public class WrongService {
public WrongService() {
System.out.println("I'm in the wrong package, I must not be instantiated");
}
}
答案 0 :(得分:2)
使用具有 basePackages 属性的自定义注释@EnableAnnotation
@EnableAnnotation(basePackages = "write-here-a-base-package")
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class SampleSimpleApplication implements CommandLineRunner {
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleSimpleApplication.class, args);
}
}
@EnableAnnotation 的定义如下:
@Retention(RUNTIME)
@Target(TYPE)
@Import(EnableAnnotationConfigRegistrar.class)
public @interface EnableAnnotation {
String[] basePackages() default "*";
@AliasFor(annotation = Import.class, attribute = "value")
Class<?>[] value() default { EnableAnnotationConfigRegistrar.class };
}
最后, EnableAnnotationConfigRegistrar.class 以编程方式进行扫描:
public class EnableAnnotationConfigRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata enableAnnotationMetadata,
BeanDefinitionRegistry registry) {
AnnotationAttributes enableAnnotationAttributes = new AnnotationAttributes(
enableAnnotationMetadata.getAnnotationAttributes(EnableAnnotation.class.getName()));
String[] basePackages = enableAnnotationAttributes.getStringArray("basePackages");
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(basePackages);
}
}
答案 1 :(得分:2)
在Fabio Formosa's answer的帮助下,this answer填充了丢失的位,并从@EntityScan
注释中获得了一些启发,我终于设法使它起作用。可以在https://github.com/knittl/stackoverflow/tree/spring-enable-annotation-working上找到可编译的有效示例。
简而言之:以Fabio的答案为基础,正确配置带有包含过滤器的ClassPathScanningCandidateComponentProvider
实例,然后针对所有提供的基类运行它很重要。 @AliasFor(annotation = Import.class, …)
似乎不是必需的,并且可以别名为另一个属性,例如basePackages
具有相同的注释。
最低实现如下:
@Configuration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(EnableCustom.EnableCustomConfiguration.class)
public @interface EnableCustom {
@AliasFor(attribute = "basePackages")
String[] value() default {};
@AliasFor(attribute = "value")
String[] basePackages() default {};
class EnableCustomConfiguration implements ImportBeanDefinitionRegistrar, EnvironmentAware {
private static final BeanNameGenerator BEAN_NAME_GENERATOR = AnnotationBeanNameGenerator.INSTANCE;
private Environment environment;
@Override
public void setEnvironment(final Environment environment) {
this.environment = environment;
}
@Override
public void registerBeanDefinitions(
final AnnotationMetadata metadata,
final BeanDefinitionRegistry registry) {
final AnnotationAttributes annotationAttributes = new AnnotationAttributes(
metadata.getAnnotationAttributes(EnableCustom.class.getCanonicalName()));
final ClassPathScanningCandidateComponentProvider provider
= new ClassPathScanningCandidateComponentProvider(false, environment);
provider.addIncludeFilter(new AnnotationTypeFilter(MyAnnotation.class, true));
final Set<String> basePackages
= getBasePackages((StandardAnnotationMetadata) metadata, annotationAttributes);
for (final String basePackage : basePackages) {
for (final BeanDefinition beanDefinition : provider.findCandidateComponents(basePackage)) {
final String beanClassName = BEAN_NAME_GENERATOR.generateBeanName(beanDefinition, registry);
if (!registry.containsBeanDefinition(beanClassName)) {
registry.registerBeanDefinition(beanClassName, beanDefinition);
}
}
}
}
private static Set<String> getBasePackages(
final StandardAnnotationMetadata metadata,
final AnnotationAttributes attributes) {
final String[] basePackages = attributes.getStringArray("basePackages");
final Set<String> packagesToScan = new LinkedHashSet<>(Arrays.asList(basePackages));
if (packagesToScan.isEmpty()) {
// If value attribute is not set, fallback to the package of the annotated class
return Collections.singleton(metadata.getIntrospectedClass().getPackage().getName());
}
return packagesToScan;
}
}
}