davidbrai
davidbrai

Reputation: 1229

Changing scope of many Spring beans during tests

I'm running tests using spring (SpringJUnit4ClassRunner and @ContextConfiguration). The tests are run in parallel. Some of my beans are singleton, and I would like to change them to be in scope "thread" of the tests. I want each test to have its own instance of the bean.

I've managed to it by having an applicationContext.xml file and a applicationTestContext.xml file which is used for tests. In the applicationTestContext.xml I define those beans with scope "thread".

The problem with this is that everytime we add a new bean of that type, we'll have to add it to both applicationContext.xml and applicationTestContext.xml which is pretty annoying. Is there a way to do it with less boilerplate?

Upvotes: 2

Views: 948

Answers (1)

artbristol
artbristol

Reputation: 32437

Gather up all the beans whose scope you want to customize and put them in a separate bean config file, included from both applicationContext and applicationTestContext, e.g.

<import resource="customScopedBeans.xml"/>

Then use a placeholder for the scope

<bean class="com.Foo" scope="${threadOrSingleton}" />

and declare the property differently in the parent config file.

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="properties">
      <value>threadOrSingleton=thread</value>
  </property>
</bean>

Upvotes: 3

Related Questions