Spring Context Initialization失败

时间:2014-09-17 10:07:56

标签: java spring spring-data

我几乎被困住了,我希望你们可以帮助我。不知怎的,我无法设法初始化我的春天语境。

我有这些不错的Bean配置类:

@Configuration
public class CoreConfig {

    @Bean
    public TeamService createService(TeamPersistenceService teamPersistenceService) {
    return new TeamEventHandler(teamPersistenceService);
    }
}

这一个:

@Configuration
@EnableJpaRepositories(basePackages = "de.ktv.persistence.repository", //
includeFilters = @ComponentScan.Filter(value = { TeamsRepository.class }, type =                            FilterType.ASSIGNABLE_TYPE))
@EnableTransactionManagement
public class PersistenceConfig {

    @Bean
    public TeamPersistenceService createService(TeamsRepository repository) {
    return new TeamPersistenceEventHandler(repository);
    }
}

在这个测试中,我想使用它们:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CoreConfig.class, PersistenceConfig.class })
public class CoreIntegrationTest {

@Autowired
TeamService teamService;

@Test
public void addNewTeamToTheSystem() {

    //some test

}

PersistenceConfig.class我正在使用不同的测试,它工作正常。但不知怎的,这里结合了CoreConfig.class,它无法初始化。

这是我得到的错误:

  

org.springframework.beans.factory.NoSuchBeanDefinitionException:找不到类型为[de.ktv.core.services.TeamService]的限定bean   依赖:预计至少有1个bean有资格成为autowire   这种依赖的候选人。依赖注释:   {@ org.springframework.beans.factory.annotation.Autowired(所需=真)}

我真的很感激任何帮助/提示。谢谢!

2 个答案:

答案 0 :(得分:3)

如果您没有指明相同的名称,则SpringContext无法绑定@autowired。默认情况下,bean名称将与方法名称相同,在这种情况下,他是不同的,2个选项:更改方法名称或添加属性名称!

选项1

@Bean(name = "teamService")
public TeamService createService(TeamsRepository repository) {
return new TeamPersistenceEventHandler(repository);
}

选项2

@Bean
public TeamService teamService(TeamsRepository repository) {
return new TeamPersistenceEventHandler(repository);
}

享受\ o /

答案 1 :(得分:1)

@Configuration
public class CoreConfig {
    @Autowired
    private TeamPersistenceService teamPersistenceService;

    @Bean
    public TeamService teamService() {
    return new TeamEventHandler(teamPersistenceService);
    }
}

这一个:

@Configuration
@EnableJpaRepositories(basePackages = "de.ktv.persistence.repository", //
includeFilters = @ComponentScan.Filter(value = { TeamsRepository.class }, type =                            FilterType.ASSIGNABLE_TYPE))
@EnableTransactionManagement
public class PersistenceConfig {
    @Autowired
    private TeamsRepository repository:

    @Bean
    public TeamPersistenceService teamPersistenceService() {
    return new TeamPersistenceEventHandler(repository);
    }
}

在这个测试中,我想使用它们:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { CoreConfig.class, PersistenceConfig.class })
public class CoreIntegrationTest {

@Autowired
TeamService teamService;

@Test
public void addNewTeamToTheSystem() {

    //some test

}