java Spring数据JPA未找到符合依赖项要求的bean
我将用spring data jpa
进行一个简单的测试
我有一个简单的pojo
、一个接口和一个runner
应用程序
这是我的密码:
package aa.bb.cc.repository;
@Repository
public interface ContentRepository extends CrudRepository<Content, Long>{
}
我有一个简单的POJO
:
@Entity
@Table(name = "content")
public class Content {
public Content(String name, String title, String description) {
this.name = name;
this.title = title;
this.description = description;
}
@NotNull
private String name;
@NotNull
private String title;
@NotNull
private String description;
...
}
和Application
类:
package aa.bb.cc.repository;
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
@Bean
public CommandLineRunner demo(ContentRepository repository) {
return (args) -> {
// save two contents
repository.save(new Content("name1", "title1", "description1"));
// fetch all Contents
log.info("Contents found with findAll():");
for (Content eachContent : repository.findAll()) {
log.info(eachContent.toString());
}
log.info("");
};
}
}
我的pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.185</version>
</dependency>
我得到一个例外:
org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [aa.bb.cc.repository.ContentRepository] found for dependency:
expected at least 1 bean which qualifies as autowire candidate for this
dependency. Dependency annotations: {}
我看到了一些相关的问题,但解决不了这个问题。 解决办法是什么
更新
spring-config.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<jpa:repositories base-package="aa.bb.cc.repository"/>
<context:annotation-config/>
</beans>
# 1 楼答案
根据Specializet answer,您可以添加@Repository注释:
# 2 楼答案
您的示例可以在my env中运行,无需xml配置。我必须解决的两件事是:
@Id
注释(@Id private Long id = 5l;
)的标识符字段如果您对此仍有问题,我可以将其上载到我的github存储库,并在此处发布链接
# 3 楼答案
我建议您阅读official documentation,您需要在spring配置中激活存储库包,如下所示:
# 4 楼答案
试着把
ContentRepository
、Content
和Application
放在同一个包中。如果您需要不同的软件包,请在Application
上添加以下注释: