2

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

这是我的代码:

(球衣类)@Component @Path("skills") public class 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> {
}

弹簧配置类:

@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)...

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

4

1 回答 1

7

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

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

或者

@EnableMongoRepositories("com.headlezz.repository")

应该做的伎俩。

于 2014-11-14T16:08:26.893 回答