【问题标题】:Bean definition in junit configuration filejunit配置文件中的bean定义
【发布时间】:2012-05-23 07:48:57
【问题描述】:

我正在使用 junit 来测试我的一些服务。我使用 spring 来注入服务及其所有依赖项。我的测试类如下所示。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/location/MyServiceTest-context.xml"})
@Transactional
public class MyServiceTest extends TestSupport {

    @Autowired
    private MyService myService;

    @Test
    public void testX() throws Exception {
        ...
    }
}

配置文件为:

<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"
       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">


     <bean id="entityBasePackages" class="java.lang.String">
         <constructor-arg value="com.package1.model"/>
     </bean>

     <bean id="bean1" class="org.easymock.EasyMock" factory-method="createMock">
         <constructor-arg value="com.package2.bean1"/>
     </bean>

     <bean id="bean2" class="org.easymock.EasyMock" factory-method="createMock">
         <constructor-arg value="com.package3.bean2"/>
     </bean>

     <context:component-scan base-package="com.package4.MyService"/>

 </beans>

MyService 使用 bean1。 bean1 依赖于 bean2,即它使用它。当我像这样运行我的测试时,它工作正常。但是,如果我在配置 xml 中将 bean2 声明在 bean1 之上,则测试失败并显示

org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.package2.bean1]

我猜 Spring 会读取文件,当它到达一个 bean 定义时,会尝试连接它——这就是它在我的情况下崩溃的原因。有没有办法告诉 Spring 读取整个文件,然后尝试连接 bean?这样我就可以编写我的 bean 定义而不用担心它们的顺序。谢谢

【问题讨论】:

  • 顺序无关紧要! Spring 不会立即尝试连接,它会从可用配置(bean 定义)创建元数据,然后开始将 bean 连接在一起。您说 bean1 依赖于 bean2,但这里似乎都是模拟,对吧?您能显示将模拟连接在一起的配置吗?

标签: spring junit autowired


【解决方案1】:

我意识到 bean1 和 bean2 不是最佳选择的名称。但这是我使用它们的方式:

@Service("bean1")
public class Bean1{

    ...

    @Validators(value = {
            @Validator(validatorClass = Bean2.class, parameters = {@Parameter(0)}, shortCircuit = true)})
    public void someMethod(SomeObject someObject){
         ...
    }

    ...
}

MyService 在内部使用 bean1 服务。

【讨论】:

    猜你喜欢
    • 2012-10-28
    • 1970-01-01
    • 2010-12-20
    • 2015-11-03
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2019-01-29
    • 2017-11-29
    相关资源
    最近更新 更多