类文件
package com.imooc.resource;
import java.io.IOException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
public class MoocResource implements ApplicationContextAware {
private ApplicationContext applicationContext;
//得到applicationContext,实现ApplicationContextAware接口
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
public void resource() throws IOException {
Resource resource = applicationContext.getResource("config.txt");
// 不写的时候,依赖applicationContext,默认为classpath
// Resource resource = applicationContext.getResource("file:/usr/config.txt");
// Resource resource = applicationContext.getResource("classpath:config.txt");
System.out.println(resource.getFilename());
System.out.println(resource.contentLength());
}
}
测试类
package com.imooc.test.resource;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.BlockJUnit4ClassRunner;
import com.imooc.resource.MoocResource;
import com.imooc.test.base.UnitTestBase;
@RunWith(BlockJUnit4ClassRunner.class)
public class TestResource extends UnitTestBase {
public TestResource() {
super("classpath:spring-resource.xml");
}
@Test
public void testResource() {
MoocResource resource = super.getBean("moocResource");
try {
resource.resource();
} catch (IOException e) {
e.printStackTrace();
}
}
}