来自Interface的Spring代理bean

时间:2013-07-04 13:39:04

标签: spring

通过接口创建代理bean的正确方法是什么?

public class JdbiRepositoryAnnotationBeanPostProcessorTest {

   private DBI dbi = mock(DBI.class);


   @org.junit.Test
   public void testIncompleteBeanDefinition() {
      AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
      ctx.register(JdbiRepositoryAnnotationBeanPostProcessor.class);
      ctx.register(MyConfig.class);
      ctx.refresh();
      ITest bean = ctx.getBean(ITest.class);
      assertNotNull(bean);
   }


   @JdbiRepository
   public static interface ITest {

   }


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

   }


}

我尝试过豆后处理器,但它没有帮助我。

编辑:

我想通过包含注释过滤器来使用组件扫描,但它也没有帮助我。

编辑:

我想通过另一个创建代理bean的库来创建实例:

TestInterface proxy = factory.onDemand(TestInterface.class);

编辑:

我为InstantiationAwareBeanPostProcessorAdapter延长了JdbiRepositoryAnnotationBeanPostProcessor。 我目前只是记录。但我看不到我的接口是一个bean。

请注意,我也更改了上面的测试代码。

public class JdbiRepositoryAnnotationBeanPostProcessor implements BeanPostProcessor, BeanFactoryAware {


   private ConfigurableListableBeanFactory beanFactory;


   public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
      return bean;
   }

   @Override
   public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
      return bean;
   }


   @Override
   public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
      if(!(beanFactory instanceof ConfigurableListableBeanFactory)) {
         throw new IllegalArgumentException("AutowiredAnnotationBeanPostProcessor requires a ConfigurableListableBeanFactory");
      }
      this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
//      this.dbiMap = this.beanFactory.getBeansOfType(DBI.class);
   }

}

1 个答案:

答案 0 :(得分:0)

问题与ComponentScanning而不是PostBeanProcessor有关。 ComponentScan只扫描具体类,这就是我的处理器无法工作的原因。我必须为接口创建一个自定义导入器。