2014-10-10 76 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