在尝试构建项目时,我在测试阶段中遇到异常。
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [java.lang.String] 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),
@org.springframework.beans.factory.annotation.Qualifier(value=findUserByLogin)}
AdviceExchange
├── domain
├── dao
├── service
├── web
package com.dozortsev.adviceexchange.dao;
import com.dozortsev.adviceexchange.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import static java.lang.String.format;
import static org.springframework.transaction.annotation.Propagation.MANDATORY;
@Transactional(propagation = MANDATORY)
@Repository
public class UserDaoImpl extends GenericDaoImpl<Long, User> implements UserDao {
@Autowired
private String findUserByLogin; // Spring can't Autowired this String
public UserDaoImpl() {
this.entityClass = User.class;
}
@Override public User findByLogin(String login) {
try {
log.info(format("Finding %s by Login: %s", getEntityClass(), login));
User user = (User) getCurrentSession().createSQLQuery(findUserByLogin)
.addEntity(getEntityClass()).setString("login", login)
.uniqueResult();
if (user != null) {
log.info("Successful found");
return user;
}
log.info(format("%s not exist", getEntityClass()));
} catch (Exception e) {
log.error("Error: ", e);
}
return null;
}
}
我的 ApplicationContext 有什么问题?请帮我解决这个问题。
答案 0 :(得分:1)
如果您使用@Qualifier
,请使用
bean name="findUserByLogin"
而不是
bean id="findUserByLogin"
答案 1 :(得分:1)
我没有在测试应用程序上下文中看到dao-application-context.xml的导入。由于出于测试目的,您使用的是单独的数据源,因此您应该在真正的应用程序上下文和测试应用程序上下文中添加另外一个应用程序上下文文件和共享bean。也就是说,使用以下命令创建一个新的上下文文件shared-application-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"...>
<!-- Queries -->
<bean id="findUserByLogin" class="java.lang.String">
<constructor-arg index="0"
value="
SELECT u.* FROM
user u, badge b, user_badge ub
WHERE
u.user_id = ub.ub_user_id
AND
b.bdg_id = ub.ub_badge_id
AND
u.user_email = :login"/>
</bean>
</beans>
然后使用以下命令将其导入dao-application-context.xml和测试应用程序上下文文件中:
<import resource="classpath:/META-INF/spring/shared-application-context.xml"/>