我有一個問題讓@Autowired工作。對不起,如果我搞砸任何條款,我對Spring相對來說比較新。彈簧自動裝配和類繼承
Spring版本是3.0.5.RELEASE,和我使用的上下文:組件掃描我的豆子定義。
這工作與@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);
}
}
採用這種設置,所有我已經添加了 '實現道',我也得到一個:
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'一起使用 – 2012-02-02 05:36:19
classpath中只有一個UserDao,我使用在我的beans文件中。 –
2012-02-02 05:38:46
因爲你正在得到'NoSuchBeanDefinitionException'似乎你havnt在上下文文件中定義了bean.Can你可以發佈你的上下文文件 – 2012-02-02 05:49:11