Spring Resource之ResourceLoaderAware接口

ResourceLoaderAware接口是一个特殊的标记接口,它表示对象需要提供给一个ResourceLoader引用:

public interface ResourceLoaderAware {
 void setResourceLoader(ResourceLoader resourceLoader);
}

当一个类实现了ResourceLoaderAware接口并且被部署到一个应用的上下文中(作为一个Spring管理的bean),它被上下文当成是一个ResourceLoaderAware.这个应用上下文会调用setResourceLoaderAware,同时把自己当做是从参数(记住所有在Spring中的应用上下文实现了ResourceLoader接口)。当然了,因为一个ApplicationContext是一个ResourceLoader,所以bean可以实现ApplicationContextAware接口并且直接使用提供的应用上下文去加载资源,但是一般情况下如果只需要需要加载资源的 话最好是去使用标准的ResourceLoader接口。代码将在加载接口的资源耦合在一起,而且不是一个完整的Spring ApplicationContext接口。

在Spring2.5中,你可以通过自动注入ResourceLoader而不是实现ResourceLoaderAware接口。传统的构造器和通过类型注入的类型现在都可以通过构造器参数或者是setter方法来提供一个ResourceLoader类型的依赖。为了更加的灵活,可以考虑使用基于注解的自动注入功能(@Autowired)。

posted on 2015-03-30 20:09  叼烟斗的纤夫  阅读(1292)  评论(0编辑  收藏  举报