Spring3:如何注册我自己的资源前缀/协议

oli*_*bur 5 resources spring

我想为自定义资源前缀编写自己的Resource(来自core.io包)实现,例如"myprotocol:/root/test/foo.properties".

最初的想法是引用JCR存储库中的Apache Sling资源路径来加载一些属性文件,然后PropertyPlaceholderConfigurer可以在Spring应用程序上下文中使用它,例如:

<context:property-placeholder properties-ref="appConfig" ignore-unresolvable="true" />

<bean id="appConfig" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>jcr:/app/test/foo.properties</value>
        </list>
    </property>
</bean>
Run Code Online (Sandbox Code Playgroud)

有没有人知道如何实现这个?

谢谢你的帮助!奥利

小智 1

资源路径的解析是在 DefaultResourceLoader 类的 getResource(String) 方法中以固定方式执行的,该类是所有应用程序上下文的超类。

解决该问题的一种想法是对应用程序上下文进行子类化。

public class CustomXmlApplicationContext extends AbstractXmlApplicationContext {

    private final CustomResourceLocator customResourceLocator;

    @Override
    public Resource getResource(String location) {
        Assert.notNull(location, "Location must not be null");
        if (location.startsWith("custom:")) {
            return customResourceLocator.getResource(location);
        }
        return super.getResource(location);
    }

}
Run Code Online (Sandbox Code Playgroud)