自动装配的MongoRepository实现在应用程序启动时抛出BeanCreationException

时间:2014-11-14 15:52:14

标签: spring mongodb mongorepository

我想使用MongoRepository接口,但我有一个BeanCreationException异常。 ComponentScan和MappingBasePackage字符串已正确填充。

这是我的代码:

(泽西岛级)     @零件     @Path( “技能”)     公共课SkillREST {

    @Autowired
    private UserService userService;    

    @POST
    @Path("/{token}")
    @Produces({MediaType.APPLICATION_JSON})
    public List<Skill> addSkill(@PathParam("token") String token, Skill skill){
        return userService.getAllSkills();
    }
}

以下是存储库未正确自动装配的服务:

@Component
public class UserService {
    @Autowired
    SkillRepository skillRepository;

    public List<Skill> getAllSkills(){
        return skillRepository.findAll();
    }
}


@Repository
public interface SkillRepository extends MongoRepository<Skill, String> {
}

Spring配置类:

@Configuration
@PropertySource("classpath:mongodb.properties")
@EnableMongoRepositories
@ComponentScan("com.headlezz")
public class SpringMongoConfig extends AbstractMongoConfiguration {
    @Inject
    Environment environment;
    @Override
    public String getDatabaseName() {
        return environment.getProperty("db.name");
    }

    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient("127.0.0.1");
    }

    @Override
    protected String getMappingBasePackage() {
        return "com.headlezz.repository";
    }

}

这是输出:

2014-11-14 17:00:49.693:WARN::Failed startup of context org.mortbay.jetty.plugin.Jetty6PluginWebAppContext@73f89d76{/nonamer,/home/pooh/workspace/java/nonamer/src/main/webapp}
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.headlezz.repository.SkillRepository com.headlezz.service.UserService.skillRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.headlezz.repository.SkillRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:293)...

有人可以解释为什么会这样吗?

1 个答案:

答案 0 :(得分:7)

您应该明确指定存储库所在的包。添加

@EnableMongoRepositories(basePackages="com.headlezz.repository")

@EnableMongoRepositories("com.headlezz.repository")

应该这样做。