Spring 无法在 Controller 中自动装配存储库

Spring not able to autowire repository in Controller

我是 Spring 的新手,正在尝试使用 Spring 数据和 Spring MVC 来启动和 运行 一个简单的网络应用程序。

这是我的控制器:

package org.springbyexample.web.servlet.mvc;

@Controller
@EnableJpaRepositories
public class PersonController {

    @Autowired
    private UserRepository userRepository;

    public UserRepository getRepository() {
        return userRepository;
    }

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // code removed
 }

这是我的存储库:

package org.springbyexample.web.orm.repository;

@Repository
public interface UserRepository extends JpaRepository<Users, String> {

    Users findByUsername(String username);

}

这是我的webmvc-context.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:p="http://www.springframework.org/schema/p"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
                       http://www.springframework.org/schema/beans/spring-beans.xsd
                       http://www.springframework.org/schema/context 
                       http://www.springframework.org/schema/context/spring-context.xsd
                       http://www.springframework.org/schema/mvc
                       http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">

<context:component-scan base-package="org.springbyexample.web.servlet.mvc" />
<context:component-scan base-package="org.springbyexample.web.security" />

<jpa:repositories base-package="org.springbyexample.web.orm org.springbyexample.web.beans" entity-manager-factory-ref="emf"/>

<mvc:annotation-driven />

<mvc:view-controller path="/index.html" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/demodb" />
    <property name="username" value="root" />
    <property name="password" value="" />
</bean>

<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="org.springbyexample.web.orm" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.hbm2ddl.auto">create</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
        </props>
    </property>
    <property name="persistenceProvider">
        <bean class="org.hibernate.jpa.HibernatePersistenceProvider"></bean>
    </property>
</bean>

在 运行 使用 maven-jetty-plugin 时,出现以下错误:

2015-04-02 16:08:39.272:WARN::Nested in    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springbyexample.web.orm.repository.UserRepository org.springbyexample.web.servlet.mvc.PersonController.userRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springbyexample.web.orm.repository.UserRepository] 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)}:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springbyexample.web.orm.repository.UserRepository] 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1308)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1054)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:949)

这是我的用户实体:

package org.springbyexample.web.beans;

@Entity
public class Users {

   private Timestamp activationDate;
   private Timestamp registrationDate;
   private int isActive;
   private String role;
   private String email;
   private int userId;
   @Id
   private String username;
   private String password;
   private String fullname;
   private String tranauth;
   private String clientPIN;

   // Getters and Setters for all of them

}

感谢任何帮助。

必须在 @Configuration class 上指定 @Enable 注释。把它放在你的控制器上不会有任何效果。如果存储库接口与注释配置位于不同的包树中,您可能还需要指定一个基础包 class。

(此外,您不应该注释存储库接口;当您需要 Spring 数据修改处理时,只需使用实际 DAO classes 的注释。)

在你的xml

<jpa:repositories base-package="org.springbyexample.web.orm org.springbyexample.web.beans" entity-manager-factory-ref="emf"/>

不正确。

如果你的仓库只在包org.springbyexample.web.orm下 然后只需删除 org.springbyexample.web.beans 这样它看起来就像

同时在您的控制器中删除 getter 和 setter,因为它不需要自动装配 enoguh 来发挥魔力。

<jpa:repositories base-package="org.springbyexample.web.orm" entity-manager-factory-ref="emf"/>

你能否尝试在 class 中添加以下注释,如果你有 public static void main(String... args) 。或者只是尝试将其添加到控制器。

  @Configuration
@ComponentScan
@EnableJpaRepositories
@EnableAutoConfiguration

就我而言,通过更改(移动)

解决了问题
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/root-context.xml
    </param-value>
</context-param>

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/root-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>{code}