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

  • Spring Essentials
  • Shameer Kunjumohamed Hamidreza Sattari
  • 214字
  • 2021-07-16 13:05:48

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"/>
主站蜘蛛池模板: 灵丘县| 贺州市| 昌平区| 额尔古纳市| 凯里市| 清镇市| 金乡县| 克什克腾旗| 基隆市| 温泉县| 乐都县| 罗定市| 峡江县| 社会| 苍溪县| 高邮市| 同仁县| 长子县| 卫辉市| 孟连| 明水县| 泽普县| 连云港市| 西畴县| 湘西| 石台县| 宝鸡市| 临猗县| 山阴县| 永和县| 延寿县| 新余市| 彭泽县| 无棣县| 荥经县| 神木县| 西城区| 莱阳市| 石城县| 清水河县| 同仁县|