Autowired MongoRepository implementation throws BeanCreationException on application start

3k views Asked by At

I want to use MongoRepository interface but I have an BeanCreationException exception. ComponentScan and MappingBasePackage strings are filled correctly.

Here's my code:

(Jersey class) @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();
    }
}

Here is the service in which repository is not Autowired correctly:

@Component
public class UserService {
    @Autowired
    SkillRepository skillRepository;

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


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

Spring configuration class:

@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";
    }

}

And here is the output:

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

Can someone explain why does it happen?

1

There are 1 answers

3
helmy On BEST ANSWER

You should explicitly specify the package(s) where your repositories reside. Adding

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

or

@EnableMongoRepositories("com.headlezz.repository")

should do the trick.