Java spring resource class

Java spring resource class

The ResourceLoaderAware interface is a special marker interface, identifying objects that expect to be provided with a ResourceLoader reference.

public interface ResourceLoaderAware < void setResourceLoader(ResourceLoader resourceLoader); >

When a class implements ResourceLoaderAware and is deployed into an application context (as a Spring-managed bean), it is recognized as ResourceLoaderAware by the application context. The application context will then invoke the setResourceLoader(ResourceLoader) , supplying itself as the argument (remember, all application contexts in Spring implement the ResourceLoader interface).

Of course, since an ApplicationContext is a ResourceLoader , the bean could also implement the ApplicationContextAware interface and use the supplied application context directly to load resources, but in general, it’s better to use the specialized ResourceLoader interface if that’s all that’s needed. The code would just be coupled to the resource loading interface, which can be considered a utility interface, and not the whole Spring ApplicationContext interface.

As of Spring 2.5, you can rely upon autowiring of the ResourceLoader as an alternative to implementing the ResourceLoaderAware interface. The «traditional» constructor and byType autowiring modes (as described in Section 5.4.5, “Autowiring collaborators”) are now capable of providing a dependency of type ResourceLoader for either a constructor argument or setter method parameter respectively. For more flexibility (including the ability to autowire fields and multiple parameter methods), consider using the new annotation-based autowiring features. In that case, the ResourceLoader will be autowired into a field, constructor argument, or method parameter that is expecting the ResourceLoader type as long as the field, constructor, or method in question carries the @Autowired annotation. For more information, see Section 5.9.2, “ @Autowired ”.

6.6 Resources as dependencies

If the bean itself is going to determine and supply the resource path through some sort of dynamic process, it probably makes sense for the bean to use the ResourceLoader interface to load resources. Consider as an example the loading of a template of some sort, where the specific resource that is needed depends on the role of the user. If the resources are static, it makes sense to eliminate the use of the ResourceLoader interface completely, and just have the bean expose the Resource properties it needs, and expect that they will be injected into it.

What makes it trivial to then inject these properties, is that all application contexts register and use a special JavaBeans PropertyEditor which can convert String paths to Resource objects. So if myBean has a template property of type Resource , it can be configured with a simple string for that resource, as follows:

 id="myBean" class=". ">  name="template" value="some/resource/path/myTemplate.txt"/> 

Note that the resource path has no prefix, so because the application context itself is going to be used as the ResourceLoader , the resource itself will be loaded via a ClassPathResource , FileSystemResource , or ServletContextResource (as appropriate) depending on the exact type of the context.

If there is a need to force a specific Resource type to be used, then a prefix may be used. The following two examples show how to force a ClassPathResource and a UrlResource (the latter being used to access a filesystem file).

 name="template" value="classpath:some/resource/path/myTemplate.txt">
 name="template" value="file:/some/resource/path/myTemplate.txt"/>

Источник

Java spring resource class

Interface for a resource descriptor that abstracts from the actual type of underlying resource, such as a file or class path resource.

An InputStream can be opened for every resource if it exists in physical form, but a URL or File handle can just be returned for certain resources. The actual behavior is implementation-specific.

Method Summary
long contentLength ()
Determine the content length for this resource.
Resource createRelative (java.lang.String relativePath)
Create a resource relative to this resource.
boolean exists ()
Return whether this resource actually exists in physical form.
java.lang.String getDescription ()
Return a description for this resource, to be used for error output when working with the resource.
java.io.File getFile ()
Return a File handle for this resource.
java.lang.String getFilename ()
Return a filename for this resource, i.e.
java.net.URI getURI ()
Return a URI handle for this resource.
java.net.URL getURL ()
Return a URL handle for this resource.
boolean isOpen ()
Return whether this resource represents a handle with an open stream.
boolean isReadable ()
Return whether the contents of this resource can be read, e.g.
long lastModified ()
Determine the last-modified timestamp for this resource.
Methods inherited from interface org.springframework.core.io.InputStreamSource
getInputStream

exists

This method performs a definitive existence check, whereas the existence of a Resource handle only guarantees a valid descriptor handle.

isReadable

Return whether the contents of this resource can be read, e.g. via InputStreamSource.getInputStream() or getFile() .

Will be true for typical resource descriptors; note that actual content reading may still fail when attempted. However, a value of false is a definitive indication that the resource content cannot be read.

isOpen

Return whether this resource represents a handle with an open stream. If true, the InputStream cannot be read multiple times, and must be read and closed to avoid resource leaks.

Will be false for typical resource descriptors.

getURL

java.net.URL getURL() throws java.io.IOException

Throws: java.io.IOException — if the resource cannot be resolved as URL, i.e. if the resource is not available as descriptor

getURI

java.net.URI getURI() throws java.io.IOException

Throws: java.io.IOException — if the resource cannot be resolved as URI, i.e. if the resource is not available as descriptor

getFile

java.io.File getFile() throws java.io.IOException

Throws: java.io.IOException — if the resource cannot be resolved as absolute file path, i.e. if the resource is not available in a file system

contentLength

long contentLength() throws java.io.IOException

Throws: java.io.IOException — if the resource cannot be resolved (in the file system or as some other known physical resource type)

lastModified

long lastModified() throws java.io.IOException

Throws: java.io.IOException — if the resource cannot be resolved (in the file system or as some other known physical resource type)

createRelative

Resource createRelative(java.lang.String relativePath) throws java.io.IOException

Parameters: relativePath — the relative path (relative to this resource) Returns: the resource handle for the relative resource Throws: java.io.IOException — if the relative resource cannot be determined

getFilename

java.lang.String getFilename()

Return a filename for this resource, i.e. typically the last part of the path: for example, «myfile.txt».

getDescription

java.lang.String getDescription()

Implementations are also encouraged to return this value from their toString method.

See Also: Object.toString()

Overview Package Class Tree Deprecated Index Help
Spring for Android
PREV CLASS NEXT CLASS FRAMES NO FRAMES
SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHOD

Источник

Урок 3: Работа с ресурсами

Этот урок освещает работу с ресурсами и основан на оригинальной документации §6. Resources.

Что вам потребуется

Настройка проекта

Прежде чем вы начнете изучать этот урок, вам необходимо создать класс lessons.starter.ResourceStarter .

Введение

Стандартный Java-класс java.net.URL и стандартные обработчки различных URL префиксов к сожалению не во всём достаточно пригодны для доступа к низкоуровневым ресурсам. К примеру, нет стандартизированных реализаций URL , которые могут быть использованы для доступа к ресурсам, которые необходимо получить из classpath, либо ServletContext . Можно зарегистрировать новые обработчики для конкретных URL префиксов, но это довольно сложная задача, а интерфейс URL все ещё недостаточно функционален.

Spring предоставляет интерфейс Resource , более совместимый для низкоуровнего доступа.

public interface Resource extends InputStreamSource < boolean exists(); boolean isOpen(); URL getURL() throws IOException; File getFile() throws IOException; Resource createRelative(String relativePath) throws IOException; String getFilename(); String getDescription(); //. >
public interface InputStreamSource

Интерфейс Resource используется и в самом Spring в качестве типа аргументов во многих методах, где необходимы ресурсы. Другие методы принимают в качестве аргументов строковые значения, которые в конечном счете используются для получения ресурсов. Важно понимать, что реализации интерфейса Resource не заменяют функциональность, а являются «оберткой». Например, URLResource является «оберткой» для URL .

Встроенные реализации

Из реализаций интерфейса Resource , которые входят в состав Spring, стоит выделить следующие:

  • UrlResource — является оберткой для java.net.URL и может быть использован для доступа к любому объекту по его URL, например, файлы, HTTP или FTP ресурс и др., либо через строковое представление с соответветствующими префиксами classpath: , file: , http: , ftp: и др.
  • ClassPathResource — представляет ресурс, который может быть получен из classpath и поддерживает ресурсы как java.io.File , если они расположены в файловой системе, а не в jar
  • FileSystemResource — реализация для обработки java.io.File . Поддерживает как File , так и URL
  • ServletContextResource — реализация для обработки ServletContext ресурсов относительно корневой директории web-приложения. Поддерживает потоковый и к URL доступ. Доступ к java.io.File возможен, когда web-приложение развернуто и ресурс физически находится в файловой системе
  • InputStreamResource — реализация для обработки InputStream . Должен использоваться только тогда, когда нет доступных соответствующих реализаций интерфейса Resource или нет возможности использовать более предпочтительный вариант ByteArrayResource
  • ByteArrayResource — реализация для обработки массива байтов. Полезен для загрузки контента из любого массива байтов, не прибегая к использованию InputStreamResource

Получение ресурсов

ResourceLoader

Интерфейс ResourceLoader предназначен для реализации возврата, т.е. загрузки, экземпляров Resource .

public interface ResourceLoader

Все контексты приложения реализуют данный интерфейс. Когда вы вызываете метод getResource() в определенном контексте приложения без указания префикса, то вы получите тот тип Resource , который соответствует контексту. В качестве демонстрации, можно запустить метод src/main/java/lessons/starter/ResourceStarter#printClassResourcesByContextNoPrefix() . В методе src/main/java/lessons/starter/ResourceStarter#printClassResourcesByContextWithPrefix() на консоль отбражаются подобные результаты, но ресурс передается уже с префиксом.

public class ResourceStarter < public static final Logger LOGGER = LogManager.getLogger(ResourceStarter.class); public static void main(String[] args) throws IOException < LOGGER.info("Starting resources. "); ResourceStarter starter = new ResourceStarter(); starter.printClassResourcesByContextNoPrefix(); starter.printClassResourcesByContextWithPrefix(); >public void printClassResourcesByContextNoPrefix() < LOGGER.info("*******printClassResourcesByContextNoPrefix**********"); ApplicationContext context = new AnnotationConfigApplicationContext(); Resource resource = context.getResource("resources/log4j.properties"); LOGGER.info("AnnotationConfigApplicationContext: " + resource.getClass().getSimpleName()); context = new ClassPathXmlApplicationContext(); resource = context.getResource("resources/log4j.properties"); LOGGER.info("ClassPathXmlApplicationContext: " + resource.getClass().getSimpleName()); context = new FileSystemXmlApplicationContext(); resource = context.getResource("resources/log4j.properties"); LOGGER.info("FileSystemXmlApplicationContext: " + resource.getClass().getSimpleName()); LOGGER.info("****************************************************"); >public void printClassResourcesByContextWithPrefix() < LOGGER.info("*******printClassResourcesByContextWithPrefix*******"); ApplicationContext context = new AnnotationConfigApplicationContext(); Resource resource = context.getResource("file:resources/log4j.properties"); LOGGER.info("file: " + resource.getClass().getSimpleName()); resource = context.getResource("http://spring.io/img/favicon.png"); LOGGER.info("http: " + resource.getClass().getSimpleName()); resource = context.getResource("classpath:resources/log4j.properties"); LOGGER.info("classpath: " + resource.getClass().getSimpleName()); LOGGER.info("****************************************************"); >>

ResourceLoaderAware

Интерфейс ResourceLoaderAware обеспечивает объект ссылкой на ResourceLoader .

public interface ResourceLoaderAware

Если класс реализует интерфейс ResourceLoaderAware и развернут в контексте приложения, например, как бин, то при его сборке контекст приложения будет вызывать метод setResourceLoader() и передавать соответствующий ResourceLoader , в зависимости от типа контекста.

Получение ресурса по его пути

Если ваш контекст ClassPathXmlApplicationContext , то вы можете получить ресурс по его пути с указанием префикса classpath: или без него с учетом его местоположения в classpath. Если же вам необходимо получить ресурс по его полному пути, то вам необходимо указать префикс file: , либо ваш контекст должен быть типа FileSystemXmlApplicationContext . В качестве демонстрации, можно запустить метод src/main/java/lessons/starter/ResourceStarter#resourcePath() .

public class ResourceStarter < public static final Logger LOGGER = LogManager.getLogger(ResourceStarter.class); public static void main(String[] args) throws IOException < //. starter.resourcePath(); >public void resourcePath() throws IOException < LOGGER.info("*****************resourcePath()*********************"); LOGGER.info("context = new ClassPathXmlApplicationContext()"); ApplicationContext context = new ClassPathXmlApplicationContext(); Resource resource = context.getResource("log4j.properties"); LOGGER.info("log4j.properties exist: " + resource.getFile().exists()); // resource = context.getResource("src/main/resources/log4j.properties"); // LOGGER.info("log4j.properties exist: " + resource.getFile().exists()); //IOException resource = context.getResource("file:src/main/resources/log4j.properties"); LOGGER.info("file:src/main/resources/log4j.properties exist: " + resource.getFile().exists()); resource = context.getResource("log/log.txt"); LOGGER.info("log/log.txt exist: " + resource.getFile().exists()); resource = context.getResource("classpath:log/log.txt"); LOGGER.info("classpath:log/log.txt exist: " + resource.getFile().exists()); resource = context.getResource("file:log.txt"); LOGGER.info("file:log.txt exist: " + resource.getFile().exists()); resource = context.getResource("file:log/log.txt"); LOGGER.info("file:log/log.txt exist: " + resource.getFile().exists()); resource = context.getResource("file:src/main/resources/log/log.txt"); LOGGER.info("file:src/main/resources/log/log.txt exist: " + resource.getFile().exists()); LOGGER.info("context = new FileSystemXmlApplicationContext()"); context = new FileSystemXmlApplicationContext(); resource = context.getResource("log4j.properties"); LOGGER.info("log4j.properties exist: " + resource.getFile().exists()); resource = context.getResource("src/main/resources/log4j.properties"); LOGGER.info("src/main/resources/log4j.properties exist: " + resource.getFile().exists()); resource = context.getResource("log/log.txt"); LOGGER.info("log/log.txt exist: " + resource.getFile().exists()); resource = context.getResource("classpath:log/log.txt"); LOGGER.info("classpath:log/log.txt exist: " + resource.getFile().exists()); resource = context.getResource("file:log.txt"); LOGGER.info("file:log.txt exist: " + resource.getFile().exists()); resource = context.getResource("file:log/log.txt"); LOGGER.info("file:log/log.txt exist: " + resource.getFile().exists()); LOGGER.info("****************************************************"); >>

Итог

Несмотря на небольшой объем урока, вы познакомились с основами доступа к ресурсам встроенными в Spring средствами. В соответствии с тем, что уроки не предусматривают работу с XML-конфигурациями, а только c Java-конфигурациями, не были рассмотрены варианты указания различных шаблонов в конструктор XML-конфигурациии, но вам ничто не мешает при необходимости ознакомиться с соответствующими разделами документации.

Источник

Читайте также:  Как получить cookie javascript
Оцените статью