Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Component Scan for custom annotation on Interface

Tags:

spring

I have a component scan configuration as this:

   @Configuration
   @ComponentScan(basePackageClasses = {ITest.class},
                  includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = JdbiRepository.class)})
   public class MyConfig {

   }

Basically I would like to create scan interface which has JdbiRepository annotation

@JdbiRepository
public interface ITest {
  Integer deleteUserSession(String id);
}

And I would like to create proxy implementation of my interfaces. For this purpose I registered a custom SmartInstantiationAwareBeanPostProcessor which is basically creating necessary instances but the configuration above does not scan interfaces which has JdbiRepository annotation.

How can I scan interfaces by custom annotation?

Edit:

It seems that org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#isCandidateComponent is accepting only concrete classes.

/**
 * Determine whether the given bean definition qualifies as candidate.
 * <p>The default implementation checks whether the class is concrete
 * (i.e. not abstract and not an interface). Can be overridden in subclasses.
 * @param beanDefinition the bean definition to check
 * @return whether the bean definition qualifies as a candidate component
 */
protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
    return (beanDefinition.getMetadata().isConcrete() && beanDefinition.getMetadata().isIndependent());
}

Edit:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface JdbiRepository {

   /**
    * The value may indicate a suggestion for a logical component name,
    * to be turned into a Spring bean in case of an autodetected component.
    * @return the suggested component name, if any
    */
   String value() default "";
}
like image 829
Cemo Avatar asked Jul 04 '13 19:07

Cemo


1 Answers

Creating a Dummy implementation seems quite hacky to me and all the steps Cemo mentioned require a lot of effort. But extending ClassPathScanningCandidateComponentProvider is the fastest way:

ClassPathScanningCandidateComponentProvider scanningProvider = new ClassPathScanningCandidateComponentProvider(false) {
    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return true;
    }
};

Now you´re also able to scan for Interfaces with (custom) Annotations with Spring - which also works in Spring Boot fat jar environments, where the fast-classpath-scanner (which is mentioned in this so q&a) could have some limitations.

like image 104
jonashackt Avatar answered Dec 05 '22 16:12

jonashackt