【发布时间】:2017-02-17 18:59:39
【问题描述】:
我下载了简单的JPA Spring Boot tutorial,它工作得很好。但是,当我尝试在我自己的测试项目中复制这个简单的行为时,我的 Application.demo() 方法中的 bean 注入出现“无法自动装配”错误,该方法返回一个 CommandLineRunner。这个项目太简单了,我什至不知道要提交什么,但这是 POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
还有应用程序。
package com.example;
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Bean
//errors with: "Could not autowire. No beans of 'SimpRepository' type found"
public CommandLineRunner demo(SimpRepository repository) {
return (args) -> {
};
}
}
以及存储库服务:
package com.example;
public interface SimpRepository extends CrudRepository<Simp, Long> {
}
对于以下实体:
package com.example;
@Entity
public class Simp {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String value;
public Simp(String value) {
this.value = value;
}
}
【问题讨论】:
-
您需要发布错误,而不仅仅是解释它。您还需要指定所有类所在的包。
-
你可以尝试在你的 SimpRepository 界面上使用@Repository。
-
@cody123 添加注释确实可以解决问题。但我很好奇为什么它在没有它的情况下在原始演示项目中工作
-
答案已由 metacubed 提供。如果对您有帮助,您可以点赞评论。
-
这个例子对我来说很好(我做了一个新项目并复制了你的代码)。我注意到的唯一问题是您的实体应该有一个默认的无参数构造函数,但即使没有构造函数,存储库也是可注入的。确保所有类都在同一个包(或
TestApplication的子包)中,并确保您已正确构建代码。
标签: java spring maven spring-data-jpa