官术网_书友最值得收藏!

Handling resources

Spring Framework provides excellent support for accessing low-level resources, thus solving many limitations of Java's standard java.net.URL and standard handlers. The org.springframework.core.io.Resource package and its many concrete implementations form a solid foundation for Spring Framework's robust resource handling.

Resource abstraction is used extensively in Spring itself, inside many implementations of ApplicationContext—it's actually very useful to use as a general utility class by itself in your own code in order to access resources. You will find the following resource implementations that come supplied right out of the box in Spring:

Generally, you do not directly instantiate any of these resources; rather, you use a ResourceLoader interface to do that job for you. All ApplicationContext implement a ResourceLoader interface; therefore, any ApplicationContext can be used to obtain resource instances. The code for this is as follows:

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"application-context.xml"});
Resource classPathResource = ctx.getResource("classpath:scripts/tasks-schema.sql");

Resource fileResource = ctx.getResource("file:///scripts/master-data.sql");

Resource urlResource = ctx.getResource("http://country.io/names.json");

You can inject resources into your beans by simply passing the filename or URL of your resource as an argument, as shown here. ApplicationContext, which is a ResourceLoader interface, will create an instance of an appropriate resource implementation based on the URL you supply:

@Value("http://country.io/names.json")
private Resource countriesResource;

Here is the XML version of injecting a resource:

<property name="countriesResource" value="http://country.io/names.json"/>
主站蜘蛛池模板: 绥滨县| 奉节县| 磐安县| 荃湾区| 乾安县| 德化县| 井冈山市| 崇左市| 教育| 吉木乃县| 鹤岗市| 平潭县| 肇东市| 青龙| 昭通市| 武夷山市| 丰镇市| 田阳县| 新余市| 岚皋县| 会昌县| 禄劝| 林周县| 周口市| 遂昌县| 吴堡县| 永新县| 扶风县| 玉龙| 都江堰市| 清苑县| 永州市| 宽甸| 西华县| 嘉黎县| 潞城市| 舞钢市| 商洛市| 辽中县| 犍为县| 宽甸|