Junit手动/自动加载spring配置文件

Junit手动加载配置文件

配置文件在classpath下和WEB-INF下两种情况的加载:

    ApplicationContext context = new FileSystemXmlApplicationContext("WebRoot/WEB-INF/applicationContext.xml");
    new ClassPathXmlApplicationContext("applicationContext.xml");// 从classpath中加载
    new FileSystemXmlApplicationContext("classpath:地址");// 没有classpath表示当前

eg:
     // 加载spring与数据库配置的部分得到DataSource
     // ==>位置是resources下面的
    ApplicationContext context = new ClassPathXmlApplicationContext("spring/spring-config.xml");
    DataSource ds = (DataSource) context.getBean("dataSource");
    Connection connection = ds.getConnection();

Junit自动加载配置文件

    @org.springframework.test.context.ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml"})

    @org.springframework.test.context.ContextConfiguration(locations={"classpath:applicationContext.xml"})

    eg:
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration({"classpath:spring/*"})
    public class CreateDBTest {
        ...
    // 多个配置文件
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath*:/spring1.xml", "classpath*:/spring2.xml" }) 
    public class CreateDBTest {
        ...

你可能感兴趣的:(Spring)