Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 没有类型为'的合格bean;com.example.repo.UserRepository';可获得的_Java_Spring_Hibernate_Spring Data - Fatal编程技术网

Java 没有类型为'的合格bean;com.example.repo.UserRepository';可获得的

Java 没有类型为'的合格bean;com.example.repo.UserRepository';可获得的,java,spring,hibernate,spring-data,Java,Spring,Hibernate,Spring Data,这是我第一次使用SpringMVC尝试SpringDataJPA,我无法解决这个错误 错误日志 严重:将上下文初始化事件发送到类org.springframework.web.context.ContextLoaderListener的侦听器实例时发生异常 org.springframework.beans.factory.UnsatifiedPendencyException:创建名为“mainController”的bean时出错:通过字段“userRepository”表示未满足的依赖关系

这是我第一次使用SpringMVC尝试SpringDataJPA,我无法解决这个错误

错误日志

严重:将上下文初始化事件发送到类org.springframework.web.context.ContextLoaderListener的侦听器实例时发生异常 org.springframework.beans.factory.UnsatifiedPendencyException:创建名为“mainController”的bean时出错:通过字段“userRepository”表示未满足的依赖关系;嵌套异常为org.springframework.beans.factory.NoSuchBeanDefinitionException:没有“com.example.repo.UserRepository”类型的合格bean可用:至少需要1个符合autowire候选条件的bean。依赖项注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 位于org.springframework.beans.factory.annotation.AutoWiredNotationBeanPostProcessor$AutoWiredFeldElement.inject(AutoWiredNotationBeanPostProcessor.java:588) 位于org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) 位于org.springframework.beans.factory.annotation.AutoWiredNotationBeanPostProcessor.postProcessPropertyValues(AutoWiredNotationBeanPostProcessor.java:366) 位于org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264) 位于org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553) 位于org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) 位于org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) 位于org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 位于org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) 位于org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) 位于org.springframework.beans.factory.support.DefaultListableBeanFactory.PreInstanceSingleton(DefaultListableBeanFactory.java:761) 位于org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) 位于org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) 位于org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444) 位于org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326) 位于org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107) 位于org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4725) 位于org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5189) 位于org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) 位于org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1419) 位于org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) 在java.util.concurrent.FutureTask.run(FutureTask.java:266)处 位于java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 位于java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 运行(Thread.java:745) 原因:org.springframework.beans.factory.NoSuchBean定义异常:没有“com.example.repo.UserRepository”类型的合格bean可用:至少需要1个符合autowire候选条件的bean。依赖项注释:{@org.springframework.beans.factory.annotation.Autowired(required=true)} 位于org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1486) 位于org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104) 位于org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066) 位于org.springframework.beans.factory.annotation.AutoWiredNotationBeanPostProcessor$AutoWiredFeldElement.inject(AutoWiredNotationBeanPostProcessor.java:585) ... 还有24个

UserRepository.java

 @Repository
 public interface UserRepository extends CrudRepository<User, Integer> {

 }
@Controller
@RequestMapping("/")
public class MainController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/user", method = RequestMethod.POST, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<User> addUser(@RequestBody User user) {
        userRepository.save(user);
        System.out.println("------>>>>>>>>>>" + user.getName());
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<User>(headers, HttpStatus.OK);
    }

    @RequestMapping(value = "/user/list", method = RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = (List<User>)userRepository.findAll();
        if (users.isEmpty()) {
            System.out.println("List is empty oops..!!");
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
        }
        System.out.println("Got the List...!!");
        System.out.println("Name of First User---->>>>" + users.get(0).getName());
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }

}
@Configuration
@ComponentScan("com.example")
@EnableWebMvc
@EnableJpaRepositories
@EnableTransactionManagement
public class AppConfig {

    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
        resolver.setPrefix("/WEB-INF");  
        resolver.setSuffix(".html");
        return resolver;  
    }

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring_database");
        dataSource.setUsername("root");
        dataSource.setPassword("");
        return dataSource;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory(){
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setShowSql(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan(User.class.getPackage().getName());
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager(){
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }

}
@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
    private String email;
    /*Getters and Setters*/
User.java

 @Repository
 public interface UserRepository extends CrudRepository<User, Integer> {

 }
@Controller
@RequestMapping("/")
public class MainController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/user", method = RequestMethod.POST, headers = "Accept=application/json")
    @ResponseBody
    public ResponseEntity<User> addUser(@RequestBody User user) {
        userRepository.save(user);
        System.out.println("------>>>>>>>>>>" + user.getName());
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<User>(headers, HttpStatus.OK);
    }

    @RequestMapping(value = "/user/list", method = RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = (List<User>)userRepository.findAll();
        if (users.isEmpty()) {
            System.out.println("List is empty oops..!!");
            return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
        }
        System.out.println("Got the List...!!");
        System.out.println("Name of First User---->>>>" + users.get(0).getName());
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }

}
@Configuration
@ComponentScan("com.example")
@EnableWebMvc
@EnableJpaRepositories
@EnableTransactionManagement
public class AppConfig {

    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
        resolver.setPrefix("/WEB-INF");  
        resolver.setSuffix(".html");
        return resolver;  
    }

    @Bean
    public DataSource dataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring_database");
        dataSource.setUsername("root");
        dataSource.setPassword("");
        return dataSource;
    }

    @Bean
    public EntityManagerFactory entityManagerFactory(){
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setShowSql(true);
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan(User.class.getPackage().getName());
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager(){
        JpaTransactionManager txManager = new JpaTransactionManager();
        txManager.setEntityManagerFactory(entityManagerFactory());
        return txManager;
    }

}
@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Integer id;
    private String name;
    private String email;
    /*Getters and Setters*/
这是我的项目结构


我错过了什么?还是我的错在这里?有人能解决这个问题吗?

您需要告诉spring在哪里查找存储库:


@EnableJpaRepositories(basePackageClasses=UserRepository.class)

您需要告诉我们每个类的包。
@ComponentScan(“com.exampl”)
missing@JBNizet我已经附上了我的项目的形象structure@RC. 补充说,仍然得到相同的错误,我有同样的问题,作为迪尚。尝试过这个,但没有改变任何东西。