【问题标题】:Spring 3 @Autowire in tests测试中的 Spring 3 @Autowire
【发布时间】:2011-11-17 10:35:02
【问题描述】:

我现在有一个恼人的问题。 由于自动接线,我的测试失败了。

无法自动装配字段:private k.dao.CompanyDao k.dao.CompanyDaoTest.companyDao;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为 [k.dao.CompanyDao] 的匹配 bean:预计至少有 1 个 bean 符合此依赖项的自动装配候选条件。

我认为@ContextConfiguration 可能是问题所在?

测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:**/servlet-context.xml", "classpath:**/root-context.xml", "classpath:**/ccc-jpa.xml" })
public final class CompanyDaoTest {

    @Autowired
    private CompanyDao companyDao;

    @Test
    public void testTest() {

    }
}

公司道

public interface CompanyDao extends GenericDao<Company> {

}

CompanyDaoJpa

@Repository("companyDao")
public class CompanyDaoJpa extends GenericDaoJpa<Company> implements CompanyDao {

    public CompanyDaoJpa() {
        super(Company.class);
    }
}

通用道

public interface GenericDao<T extends DomainObject> {

    public T get(Long id);

    public List<T> getAll();

    public T save(T object);

    public T delete(T object);

}

servlet-context.xml

    <annotation-driven />

    <context:component-scan base-package="k"/>

【问题讨论】:

  • 其他 Spring XML 配置是什么样的?

标签: java spring-3 spring-test


【解决方案1】:

我猜你的测试根本没有加载servlet-context.xml。

您将servlet-context.xml 引用为类路径资源,但servlet-context.xml 通常位于WEB-INF 下,它不是应用程序类路径的一部分。请注意,当使用通配符 (classpath:**/servlet-context.xml) 引用配置文件时,Spring 不会抱怨缺少配置文件,因此即使找不到配置文件,您的测试也会静默启动。

没有很好的方法可以从单元测试中访问位于WEB-INF 中的 Spring xml 文件。如果要对它们运行测试,则需要将它们移动到类路径(即移动到 src 或 resources,具体取决于您的项目布局)。由于DispatcherServlet 和ContextLoaderListener 期望在WEB-INF 下找到这些文件,因此您还需要使用它们各自的contextConfigLocation 参数重新配置它们。比如DispatcherServlet的情况:

<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:**/servlet-config.xml</param-value>
</init-param>

【讨论】:

  • 谢谢,这就是问题所在:)
猜你喜欢
  • 2013-06-15
  • 1970-01-01
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 2013-02-06
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
相关资源
最近更新 更多