为什么自动装配Spring仓库不起作用? [英] 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
}
我的存储库扩展了CrudRepository
My repository extends CrudRepository
@Repository
public interface AccountRepository extends CrudRepository<Account, Integer> {
Account findOne(int primaryKey);
}
我使用xml来配置我的项目.在这里:
I use xml to configure my project. 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>
为什么不起作用?我收到的错误是AccountController无法自动装配bean AccountRepository.
Why it doesn't work? The error I receive is that AccountController cannot autowire bean AccountRepository.
编辑 我已经将配置重构为基于注释的内容,并且一切正常.在我的XML版本中,我可能没有扫描某些类,并且导致错误.
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.
推荐答案
可能是您需要在配置类上使用 @Configuration 注释添加 @EnableJpaRepositories 注释,而不是控制器类.
May be you need to have @EnableJpaRepositories annotation on a configuration class with @Configuration annotation instead of Controller class.
还要确保您的配置类在扫描的软件包下.
Also, make sure your Configuration classes are under a scanned package.
这篇关于为什么自动装配Spring仓库不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!