【发布时间】:2012-02-24 19:47:57
【问题描述】:
我在让@Autowired 工作时遇到问题。对不起,如果我搞砸了任何条款,我对 Spring 比较陌生。
Spring 版本是 3.0.5.RELEASE,我在我的 beans 定义中使用 context:component-scan。
这适用于 @Autowired 注释:
@Component
public class UserDao {
@PersistenceContext
protected EntityManager em;
@Transactional
public User findById(Long id) {
return em.find(User.class, id);
}
}
这不适用于 @Autowired 注释:
@Component
public class UserDao implements Dao<User> {
@PersistenceContext
protected EntityManager em;
@Transactional
public User findById(Long id) {
return em.find(User.class, id);
}
}
通过这个设置,我添加了“implements Dao”,我得到了:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [web.rs.persistence.dao.UserDao] 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)}
还有一些其他类供参考:
Dao.java(接口):
public interface Dao<T extends BaseEntity> {
T findById(Long id);
}
UserResource.java:
@Component
public class UserResource {
@Autowired
UserDao userDao;
public User getUser(Long id) {
return userDao.findById(id);
}
}
applicationContext.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="web.rs" />
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config.properties" />
</bean>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="persistenceUnitName" value="${persistence.unit}" />
</bean>
<bean id="trx-manager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<tx:annotation-driven transaction-manager="trx-manager" />
</beans>
谁能解释一下这个问题?我很想保留类继承。
谢谢!
【问题讨论】:
-
您是否在上下文文件中定义了 bean?如果您有多个 UserDao bean,请尝试使用
@qualifier和@autowire -
类路径中只有一个UserDao,我的beans文件中使用的是
。 -
当您收到
NoSuchBeanDefinitionException时,您似乎没有在上下文文件中定义 bean。请您发布您的上下文文件 -
已发布。我已经在没有
<bean id="userDao" class="web.rs.persistence.dao.UserDao"/>的情况下尝试了它,但没有运气。请记住,仅添加接口就会使其中断。 -
尝试使用@Repository 而不是@Component 同时检查根异常还是这是您日志中唯一的异常?
标签: spring inheritance autowired