观看慕课moocer老师视频Spring Bean装配之Resource

classpath:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd"
        default-autowire= "constructor">
        
        <bean id= "moocResource" class="com.imooc.resource.MoocResource"></bean>
        
</beans>
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.ioc.interfaces.UnitTestBase;
import com.imooc.resource.MoocResource;

@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();
		}
	}
}
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;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
		
	}
	
	public void resource() throws IOException{
		Resource resource=applicationContext.getResource("classpath:config.txt");
		System.out.println(resource.getFilename());
		System.out.println(resource.contentLength());
		
	}

}

运行结果:

file:

获取路径:

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;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext=applicationContext;
		
	}
	
	public void resource() throws IOException{
		Resource resource=applicationContext.getResource("file:D:\\技术\\爬虫\\java\\Spring\\src\\config.txt");
		System.out.println(resource.getFilename());
		System.out.println(resource.contentLength());
		
	}

}

不加前缀,即以来applicationContext的创建方式,即依赖classpath的方式:

但是关于url方式,我输出网址是很奇怪的:

原因是:getContentLength获取文件大小的原理就是头中的content length属性,如果服务器没有或者流不支持,就返回-1了。

原文链接:加载失败,请重新获取