2014-10-10 75 views
1

我喜歡Play Framework 2的許多功能(我正在使用它與Java),但作爲依賴注入的粉絲,我也喜歡Spring,特別是它的注入配置到對象的方式只使用@Value註釋。彈性屬性注入與Play2框架

因此,我很想知道如何使用Play的內置屬性解析機制將屬性的值注入到實例變量中。就像這樣:

@Component 
public class SpringBeanWithinAPlay2Application { 

    @Value("${application.timeout:10}") 
    private int timeout; 
} 

任何線索的人? 非常感謝提前。

回答

2

我前一陣子有同樣的問題,這是我做這個工作的方式:

首先,當你自舉你的Spring應用程序上下文(我用基於註解的配置,但同樣要基於XML工作) ,你必須添加一個自定義的PropertySource,這是Spring支持添加新的解析屬性的方式。事情是這樣的:

public static void initialize() { 
    ctx = new AnnotationConfigApplicationContext(); 
    ctx.getEnvironment().getPropertySources().addFirst(new PlayFrameworkPropertySource()); 
    ctx.scan("somepackage"); 
    ctx.refresh(); 
} 

自定義類PlayFrameworkPropertySource是確實的魔力之一:

public class PlayFrameworkPropertySource extends PropertySource<Object> { 

    public PlayFrameworkPropertySource() { 
     super("Play Framework properties resolution mechanism"); 
    } 

    @Override 
    public Object getProperty(String propertyName) { 
     // or ConfigFactory.load().getString(propertyName), as you prefer... 
     return Configuration.root().getString(propertyName); 
    } 
} 

爲了讓這一切的工作,你只需要做一件事:明確聲明PropertySourcesPlaceholderConfigurer類型的一些@Configuration類豆你可能會使用:

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

重要提示:該豆必須是static,因爲它是BeanFactoryPostProcessor,它應該在任何其他常規@Bean之前加載。

這對我來說就像一個魅力,希望這對別人有幫助!

乾杯,
喬納森

+0

感謝。它爲我做了詭計! – Khaleesi 2014-10-13 01:04:09