在一个Spring MVC + JPA/Hibernate的训练项目中,我在更改配置后得到了这个错误。
最初的DAO类是这样的:
public Course getById(Integer id) throws DAOException {
Course result = null;
try {
EntityManager em = emf.getFactory().createEntityManager();
result = em.find(Course.class, id);
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new DAOException("Could not get Course By Id", e);
}
return result;
}
我被告知要用@PersistenceContext
生成 * BattyManager *,并避免不时地创建新的BattyManager。因此,我将上面的EntityManager em = ...
行替换为@Autowired EntityManager em;
字段,并更改了JpaConfig类,因此它看起来像:
@Configuration
@ComponentScan(basePackages = "com.example.school")
@PropertySource("classpath:database.properties")
@EnableTransactionManagement
public class JpaConfig {
private final Environment environment;
@Autowired
public JpaConfig(Environment environment) {
this.environment = environment;
}
@Autowired
DataSource dataSource;
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws NamingException {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource);
em.setPackagesToScan("com.example.school");
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
return em;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
以前的配置文件就是这么简单:
@Configuration
public class EntityManagerConfig {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("PU");
@Bean
EntityManager em() {
return emf.createEntityManager();
}
}
现在我得到了一个堆栈跟踪,其中有以下最重要的问题:
org.springframework.beans.factory.UnsatisfiedDependencyException.
...
原因:org.springframework.beans.factory.BeanNotOfRequiredTypeException:名为'courseDAO'的Bean应该是'com.example.school.dao.CourseDAO'类型,但实际上是org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1317)中的'com.sun.proxy.$Proxy49'类型
这种配置可能有什么问题?
1条答案
按热度按时间gwbalxhn1#
如果您将bean命名为
entityManagerFactory
,则可能会破坏依赖于HibernateEntityManagerFactory
类型的其他bean。例如,将其重命名为localContainerEntityManagerFactory
。