2017-09-28 99 views
2

長話短說:

有沒有辦法解釋從${my.property}@Value註釋內的規劃環境地政司的表達而產生,而不使用字符串轉換器,例如像@Value("#{${my.property}})?


我有一個抽象工廠(簡體),讓我建立這是我的系統的配置的一部分,一些常見的物品。

@Component 
public class Factory { 
    public Product makeVal(int x) { return new Product(5); } 
} 

爲了更加靈活,我想,讓用戶寫在app.properties文件規劃環境地政司的表達,使工廠可以直接訪問:現在

my.property = @Factory.makeVal(12) 

,在類需要這個屬性,爲了達到我的目標,我寫了下面的代碼。

@Value("#{${my.property}}") 
private Product obj; 

我認爲${my.property}將是宏擴展,然後通過在上面的例子#{}作爲相應的使用SpEL表達,@Factory.makeVal(12)評價。不幸的是,情況並非如此,加載Spring上下文導致錯誤,表明它無法將字符串(屬性值${my.property})轉換爲目標類型Product

現在,我通過編寫實現Converter<String, Product>的類來解決這個問題,但它非常複雜,因爲我需要通過實例化ExpressionParser等以編程方式評估字符串爲SpEL表達式。

但有沒有更簡單的解決方案?是否有一個單獨的SpEL表達式可以放入@Value註釋中,讓我簡單地將${my.property}作爲SpEL表達式自行評估?

回答

2

也許這只是一個替換@Factoryfactory屬性值的問題。這個測試通過我:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(classes = { SpelTest.Config.class }) 
public class SpelTest 
{ 
    @Value("#{${my.property}}") 
    Product _product; 

    @Test 
    public void evaluating_spel_from_property_value() throws Exception 
    { 
     Assert.assertEquals(1234, _product.value); 
    } 

    @Component 
    public static class Factory 
    { 
     public Product makeVal(int x) { return new Product(x); } 
    } 

    public static class Product 
    { 
     public final int value; 

     public Product(final int value) { this.value = value; } 
    } 

    @Configuration 
    @ComponentScan(basePackageClasses = SpelTest.class) 
    public static class Config 
    { 
     @Bean 
     public Factory factory() { return new Factory(); } 

     @Bean 
     public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() { 
      final PropertySourcesPlaceholderConfigurer psc = new PropertySourcesPlaceholderConfigurer(); 
      final MutablePropertySources sources = new MutablePropertySources(); 
      sources.addFirst(new MockPropertySource() 
       .withProperty("my.property", 
          "factory.makeVal(1234)")); 
      psc.setPropertySources(sources); 
      return psc; 
     } 
    } 
}  
+1

哎喲,我完全錯了。除了我忘記提及的事實之外,我明確指定了一個bean名稱「Factory」而不是隱藏「factory」,它看起來是我得到的原始錯誤來自完全不同的註釋。太累了,太累XD我會盡快刪除這個問題,因爲事實上它沒有任何意義。無論如何感謝:D –

+0

原來我太遲了刪除它,哈哈。哦,好吧......:D –

相關問題