2.5ResourceLoaderAware接口

ResourceLoaderAware接口是一个特殊的回调,表明该组件需要提供一个ResourceLoader的引用。 下面是ResourceLoaderAware的定义:

public interface ResourceLoaderAware {

    void setResourceLoader(ResourceLoader resourceLoader);
}

当一个类实现了ResourceLoaderAware并被部署到application context,那么整个类就被识别为ResourceLoaderAware。 application context会去调用setResourceLoader(ResourceLoader)方法,并将其自身作为参数传入(所有的Spring application contexts 都实现了ResourceLoader 接口)。

因为ApplicationContext也是ResourceLoader,bean也可以实现ApplicationContextAware接口,然后直接使用提供的application context来加载资源。但是通常来说还是使用ResourceLoader来管理资源(代码会被转换为ResourceLoader而不是整个的ApplicationContext)。

在应用程序组件中,你也可以使用自动装载ResourceLoader,来替代使用ResourceLoaderAware接口。可以使用传统的constructor或者byType的自动装载模式。但是使用基于注解的自动装载可操作性更好。 在这种情况下,ResourceLoader 被自动注入到ResourceLoader类型的字段,构造函数参数,或者方法参数, 只要他们使用了@Autowired注解。

最后更新于