简体   繁体   中英

Spring Application Context - Main and Test Folders

I have a Spring project with 4 typical source folders - main/src , main/resources , test/src and test/resources . When I run my application, Spring fetches the application-context file in main/resources and if I run any Junit test, it fetches the application-context.xml file under test/resources . How does Spring fetch the application-context.xml file appropriately or is there any config involved?

Try running any other project with jsf or with Struts , they will also pick resources from respective folders. It has nothing to do with spring. It will be taken care by maven or any other build system you are using.

main/src , main/resources , test/src , test/resources 

these folders are standard when you create maven or gradle project.

The application tells Spring where the application context is. Web applications do this by configuring a ContextLoaderListener in the web.xml. For each test how your application context gets loaded is part of the test's configuration, the @ContextConfiguration annotation specifies how the context gets loaded from what location or from what annotated classes.

For instance if I set up the test to use

@ContextConfiguration(loader = AnnotationConfigContextLoader.class,
classes = MyTest.ContextConfiguration.class)
public class MyTest {
    @Autowired MyStuff stuff;

    static class ContextConfiguration {
        @Bean public MyStuff getMyStuff() {
            return new MyStuff();
        }
    }
}

then MyTest uses the annotations in the test to decide what to inject into, and populates those fields using the specified ContextConfiguration. It totally disregards any xml configuration in the classpath.

The context loader can also specify locations to load the context from, see the documentation for org.springframework.test.context.ContextLoader .

You don't say what version of Spring you're using. Prior to 3.0 tests managed test contexts by implementing the abstract method loadContext of the class org.springframework.test.AbstractSpringContextTests, which was part of the hierarchy that spring-aware tests extended.

I know this question is old but with Spring-boot 2.x the folder structure is different. This is what I get from Spring initializer and IntelliJ:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM