2012-09-01 106 views
1

我有一個標準的bean,需要自動裝配一些屬性。Spring Spring Autowire在BeanFactoryPostProcessor中創建的bean

@Service 
public class MyServiceImpl implements MyService { 

    @Autowired 
    private FirstRepository first; 

    public MyServiceImpl() { 

    } 

我使用Java配置找到豆:

@Configuration 
@ComponentScan(basePackages = "com.company", excludeFilters = { @Filter(Configuration.class) }) 
public class MainConfig { 
} 

然而,FirstRepository豆不存在,所以我在BeanFactoryPostProcessor的創建:

public class RepoGeneratorPostProcessor implements BeanFactoryPostProcessor { 

    public void postProcessBeanFactory(
      ConfigurableListableBeanFactory beanFactory) throws BeansException { 

     GenericBeanDefinition jpaR = new GenericBeanDefinition(); 
     jpaR.setBeanClass(JpaRepositoryFactoryBean.class); 
     jpaR.setAutowireCandidate(true); 
     jpaR.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE); 
     jpaR.setLazyInit(false); 
     jpaR.setPropertyValues(new MutablePropertyValues().add("repositoryInterface", FirstRepository.class)); 

     RootBeanDefinition definition = new RootBeanDefinition(); 
     definition.setBeanClass(FirstRepository.class); 
     definition.setAutowireCandidate(true); 
     definition.setFactoryBeanName("&jpaR"); 
     definition.setFactoryMethodName("getObject"); 
     definition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_NAME); 
     definition.setLazyInit(false); 
     definition.setAttribute(RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE); 


     BeanDefinitionRegistry registry = (BeanDefinitionRegistry)beanFactory; 
     registry.registerBeanDefinition("jpaR", jpaR); 
     registry.registerBeanDefinition("first", definition); 

} 

當我啓動我的應用程序我得到以下異常,似乎表明Spring無法找到FirstRepository bean。

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.company.FirstRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. 

如果我刪除@Autowired註釋,我可以看到啓動後FirstRepository bean已正確創建。

有什麼建議嗎?

回答

0

這個例外是說當項目正在構建時沒有爲FirstRepository類定義bean。 我在這裏也看不到它。

最簡單的解決辦法是有一個bean定義在application-context.xml這樣的:

<bean id="firstRepository" class="your.package.FirstRepository" autowire="byName"/> 

在這種情況下,在啓動時,會出現該bean定義。

+0

對不起,如果我不清楚。問題的關鍵是必須在BeanFactoryPostProcessor中創建bean。它不能被添加到application-context.xml中。 – dough