Java 无法自动关联字段,但我有定义
我的app-config.xml为我的userdaobean提供了一个定义:Java 无法自动关联字段,但我有定义,java,hibernate,spring,spring-mvc,Java,Hibernate,Spring,Spring Mvc,我的app-config.xml为我的userdaobean提供了一个定义: <bean id="userDao" class="com.blah.core.db.hibernate.UserDaoImpl"> <property name="sessionFactory" ref="sessionFactory"/> </bean> “getTestUser()”是一个引用UserDao的新方法,它看起来像: @Service
<bean id="userDao" class="com.blah.core.db.hibernate.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
“getTestUser()”是一个引用UserDao的新方法,它看起来像:
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
public String sayHello() {
return "hello from user service impl part 2";
}
public String getTestUser() {
return userDao.getById(1L).getUsername();
}
}
我得到一个错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.blah.core.db.hibernate.UserDao com.blah.core.services.UserServiceImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.blah.core.db.hibernate.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)}
您是否尝试过导出Spring的所有注册bean(或通过读取或内存),以确定
userDao
bean是否在列表中。请确保UserDaoImpl
也真正实现了UserDao
——我指的是这一点,因为我在这里没有看到UserDaoImpl
的片段
如果您不使用
@Autowired
,另一种方法是通过ApplicationContext(这被认为是一种肮脏的方式,请改为修复您的@Autowired
)通过bean名称、类名等显式获取bean的引用。好的,我没有实现UserDao啊!谢谢顺便说一句,你如何通过调试读取spring的引导日志或内存?)这些都是我应该学习的好技能!我已更新了有关日志记录和调试的答案。:)
@Service
public class UserServiceImpl implements UserService{
@Autowired
UserDao userDao;
public String sayHello() {
return "hello from user service impl part 2";
}
public String getTestUser() {
return userDao.getById(1L).getUsername();
}
}
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.blah.core.db.hibernate.UserDao com.blah.core.services.UserServiceImpl.userDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.blah.core.db.hibernate.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)}