Kramer
Kramer

Reputation: 1058

Programmatic access to application context and context locations

I have some tests (I didn't write them, I am maintaining them) that use the spring ContextConfiguration annotation to supply application contexts:

@ContextConfiguration(locations = { "testCustomContext.xml" })
public class MyTest  {
}

Anyway, a couple of questions. I am not so familiar with spring custom context locations that don't specify file:/ or classpath:/. What does it mean? There are a lot of resources on this test class path with that name. Are they all loaded? If not, how does Spring know which to load?

Second, is there a way to programmatically access a spring context that has been wired in this way?

I.e. is there a static Spring Class or ThreadLocal variable that would give me access to the current context?

Thanks in advance for the help.

Upvotes: 2

Views: 1031

Answers (1)

Maciej Ziarko
Maciej Ziarko

Reputation: 12084

You can gain access to application context by just autowiring it inside test class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class MyTest {

    @Autowired
    private ApplicationContext applicationContext;

    // class body...
}

As for your second question:

I am not so familiar with spring custom context locations that don't specify file:/ or classpath:/. What does it mean? There are a lot of resources on this test class path with that name. Are they all loaded? If not, how does Spring know which to load?

From Java Docs:

A plain path — for example, "context.xml" — will be treated as a classpath resource that is relative to the package in which the specified class is defined. A path starting with a slash is treated as an absolute classpath location, for example: "/org/springframework/whatever/foo.xml". A path which references a URL (e.g., a path prefixed with classpath:, file:, http:, etc.) will be added to the results unchanged.

You can learn about Spring Resources in docs: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/resources.html

Also JavaDocs for @ContextConfiguration can give you more knowledge.

I encourage you to study Spring Docs.

Upvotes: 1

Related Questions