我是Spring的新手,我试图使用autowire将crudrepository的实例(从spring数据)转换到另一个类(仅用于测试目的,我将自动将其自动装入我的服务层)。但是,spring无法找到要自动装配的bean实例。
以下是错误消息:
Field repository in com.connor.ConnorApplication required a bean of type 'com.connor.dao.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.connor.dao.UserRepository' in your configuration.
这是运行我的spring应用程序的类的我的代码:
package com.connor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//import org.springframework.boot.autoconfigure.domain.EntityScan;
//import org.springframework.context.annotation.ComponentScan;
//import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.connor.dao.UserRepository;
@SpringBootApplication
public class ConnorApplication /*begin addition*/implements CommandLineRunner /*end addition*/{
//begin addition code
@Autowired
private UserRepository repository;
@Override
public void run(String... args) throws Exception
{
System.out.println("-------------------------------------");
long numEntries = repository.count();
System.out.println("There are " + numEntries + " entries in the user table");
System.out.println("-------------------------------------");
}
//end addition code
public static void main(String[] args) {
SpringApplication.run(ConnorApplication.class, args);
}
}
crudrepository的代码
package com.connor.dao;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.connor.model.User;
@Repository
public interface UserRepository extends CrudRepository<User, Integer>{
}
最后,这是我的文件夹结构:
的图片答案 0 :(得分:0)
这取决于您正在使用的spring-data项目(在pom.xml中查找依赖项,如spring-boot-start-data-*
),但可能需要启用您的存储库。
例如,在spring-data-mongodb中,您需要@EnableMongoRepositories
注释或application.properties或spring.xml中的等效配置。