2013-01-10 30 views
3

我正在尋找一種方法來創建自定義ResourceLoader,它將使用從HBase表讀取屬性。我發現我可以創建自己的ApplicationContext,覆蓋getResource並使用我自己的ResourceLoader。使用ClasspathXmlApplicationContext定製Spring ResourceLoader

@Override 
public Resource getResource(String location) { 
    if (location.startsWith(HbaseResource.HBASE_PREFIX)) { 
     ResourceLoader loader = (ResourceLoader)getBean(HbaseResourceLoader.class); 
     return loader.getResource(location); 
    } else{ 
     return super.getResource(location); 
    } 
} 

我正在尋找一種方式來獲得相同的結果,只有使用ClassPathXmlApplicationContext的,而不是創建自己的contxt類。 閱讀有關ResourceLoaderAware我看到這條線:

作爲替代物ResourcePatternResolver依賴性,由bean工廠考慮類型資源陣列的 暴露bean屬性,通過圖案填充 字符串與自動類型轉換。

這能以任何方式幫助我嗎? 有沒有另一種方法我錯過了註冊自定義ResourceLoader?

回答

2

ResourceLoader是一種特殊的構建塊,不能像其他容器服務那樣直接注入,但我相信你對類型轉換的觀察可以提供幫助。您可以安裝一個ConversionService(帶有名稱爲「conversionService」的bean),其中有一些適合您的功能,如果您可以確保在需要進行任何轉換之前就已經註冊了它,那麼我認爲它會起作用。你怎麼做取決於你是否使用XML或@Configuration。一個簡單的玩具例如:

@Test 
public void testResource() { 
    System.setProperty("value", "123"); 
    System.setProperty("resource", "location:not.found"); 
    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); 
    context.register(TestConfig.class); 
    context.refresh(); 
    Resource resource = context.getBean("resource", Resource.class); 
    assertTrue(resource.exists()); 
} 

@Configuration 
@Import(ConversionConfig.class) 
public static class TestConfig { 

    @Value("${resource}") 
    private Resource resource; 

    @Bean 
    public Resource resource() { 
     return resource; 
    } 

    @Bean 
    public static PropertySourcesPlaceholderConfigurer placeholders() { 
     return new PropertySourcesPlaceholderConfigurer(); 
    } 

} 

@Configuration 
public static class ConversionConfig { 

    @Bean 
    protected ConversionService conversionService(final ResourceLoader loader) { 
     GenericConversionService service = new GenericConversionService(); 
     service.addConverter(new Converter<String, Resource>() { 
      public Resource convert(String location) { 
       Resource resource = loader.getResource(location); 
       if (resource.exists()) { 
        return resource; 
       } 
       return new ByteArrayResource("foo".getBytes()); 
      } 
     }); 
     return service; 
    } 

} 
+0

一些JIRA引用:[SPR-3721](https://jira.springsource.org/browse/SPR-3721),[SPR-9505](HTTPS:// JIRA。 springsource.org/browse/SPR-9505)。正如你所看到的,這是我的一種癡迷。 –

相關問題