[英]Why autowiring spring repositories doesn't work?
I have a controller where I autowire repository: 我有一个控制器,可以在其中自动装配存储库:
@Controller
@RequestMapping("/account")
@EnableJpaRepositories
public class AccountController {
@Autowired
private AccountRepository accountRepo;
//methods
}
My repository extends CrudRepository 我的存储库扩展了CrudRepository
@Repository
public interface AccountRepository extends CrudRepository<Account, Integer> {
Account findOne(int primaryKey);
}
I use xml to configure my project. 我使用xml来配置我的项目。 Here it is: 这里是:
<jpa:repositories base-package="com.library.repositories"
entity-manager-factory-ref="entityManager"></jpa:repositories>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager" />
</bean>
<bean id="entityManager"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.library.entities" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<!-- <prop key="hibernate.hbm2ddl.auto">create-drop</prop> -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/library" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
Why it doesn't work? 为什么不起作用? The error I receive is that AccountController cannot autowire bean AccountRepository. 我收到的错误是AccountController无法自动装配bean AccountRepository。
EDIT I've refactored my configuration to annotation based and everything works. 编辑我已经将我的配置重构为基于注释,并且一切正常。 In my XML version I probably didn't scan some classes and it resulted with error. 在我的XML版本中,我可能没有扫描某些类,并且导致错误。
May be you need to have @EnableJpaRepositories annotation on a configuration class with @Configuration annotation instead of Controller class. 可能需要在具有@Configuration注释而不是Controller类的配置类上具有@EnableJpaRepositories注释。
Also, make sure your Configuration classes are under a scanned package. 另外,请确保您的配置类在扫描的软件包下。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.