spring - 组件扫描接口(interface)上的自定义注释

标签 spring

我有一个组件扫描配置,如下所示:

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

   }

基本上我想创建具有 JdbiRepository 的扫描界面注解
@JdbiRepository
public interface ITest {
  Integer deleteUserSession(String id);
}

我想创建我的接口(interface)的代理实现。为此,我注册了一个自定义 SmartInstantiationAwareBeanPostProcessor这基本上是创建必要的实例,但上面的配置不扫描具有 JdbiRepository 的接口(interface)注解。

如何通过自定义注释扫描接口(interface)?

编辑:

看来org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider#isCandidateComponent只接受具体的类(class)。
/**
 * 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());
}

编辑:
@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 "";
}

最佳答案

创建一个 Dummy 实现对我和所有步骤来说似乎很 hacky Cemo提到需要很多努力。但扩展ClassPathScanningCandidateComponentProvider是最快的方法:

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

现在您还可以使用 Spring 扫描带有(自定义)注释的接口(interface) - 这也适用于 Spring Boot fat jar 环境 ,其中 fast-classpath-scanner (在 this so q&a 中提到)可能有一些限制。

关于spring - 组件扫描接口(interface)上的自定义注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17477255/

相关文章:

java - 使用 MockMVC 测试表单时如何将集合设置为参数

java - Hibernate Search 不索引/重新索引实体

spring - 模拟 Autowired ExecutorService

java - spring jdbc 和复合主键

java - 如何使用基本身份验证阻止 tomcat 中的 servlet session ?

Spring Data MongoDB 如何使用 javaconfig 样式设置自动连接重试 ="true"?

java - 如何在java运行时创建新添加的类的实例

Spring 卡夫卡 : Poll for new messages instead of being notified using `onMessage`

java - 如何将 Spring Boot @RepositoryRestResource 映射到特定的 url?

Java:spring:为什么Abstract BeanFactory不允许更改父BeanFactory?