2
我想使用MongoRepository接口,但我有一個BeanCreationException異常。 正確填充ComponentScan和MappingBasePackage字符串。自動裝配的MongoRepository實現在應用程序啓動時拋出BeanCreationException
這裏是我的代碼:
(州級) @Component @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> {
}
彈簧配置分類:
@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 [email protected]{/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)...
有人可以解釋它爲什麼會發生?
嗨,@helmy。請使用SkillRepository從上面查看我的代碼片段。我提到了這個註釋,但沒有奏效。所以必須有另一個原因。 – Reynard 2014-11-14 16:31:09
對不起,我現在看到了。您可以嘗試將您的配置註釋更改爲@EnableMongoRepositories(basePackages =「com.headlezz.repository」) – helmy 2014-11-14 16:39:17
@helmy,您應該更新您的答案,並在'@ EnableMongoRepositories'中指定basePackages選項的信息,該信息應該有效。 – 2014-11-14 16:47:22