1

I have a standard bean with some properties that need to be autowired.

@Service
public class MyServiceImpl implements MyService {

    @Autowired
    private FirstRepository first;

    public MyServiceImpl() {

    }

I use a Java Config to find the beans:

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

However, the FirstRepository Bean doesn't exist so I create it in a 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);

 }

When I start my application I get the following exception which seems to suggest that Spring can't find the 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.

If I remove the @Autowired annotation I can see after start up that the FirstRepository bean is properly created.

Any suggestions?

4

2 回答 2

0

此异常表示FirstRepository在构建项目时没有为该类定义 bean。我在这里也看不到。

最简单的解决方案是像这样在您的 bean 定义中application-context.xml

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

在这种情况下,在启动时,会有那个 bean 定义。

于 2012-09-01T05:51:00.803 回答
0

我认为您不需要在 beanname 之前的 &

definition.setFactoryBeanName("&jpaR");

我在我的项目中使用了类似的东西

definition.setFactoryBeanName("jpaR");

它按预期工作

如果您需要首先获取 bean 的工厂 bean,则需要 & 。&first 应该返回 jpaR。

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/beans.html#beans-factory-extension-factorybean

于 2016-01-17T11:31:05.653 回答