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. For example, consider 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, have the bean expose the Resource
properties it needs,
and expect them to 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 the following example shows:
<bean id="myBean" class="...">
<property name="template" value="some/resource/path/myTemplate.txt"/>
</bean>
Note that the resource path has no prefix. Consequently, because the application context itself is
going to be used as the ResourceLoader
, the resource itself is loaded through a
ClassPathResource
, a FileSystemResource
, or a ServletContextResource
,
depending on the exact type of the context.
If you need to force a specific Resource
type to be used, you can use a prefix.
The following two examples show how to force a ClassPathResource
and a
UrlResource
(the latter being used to access a filesystem file):
<property name="template" value="classpath:some/resource/path/myTemplate.txt">
<property name="template" value="file:///some/resource/path/myTemplate.txt"/>