简体   繁体   English

Play2框架的Spring属性注入

[英]Spring Property Injection with Play2 Framework

I like many features of Play Framework 2 (I'm using it with Java) but, as a fan of Dependency Injection, I love also Spring and particularly, its way to inject configuration into objects by just using the @Value annotation. 我喜欢Play Framework 2的许多功能(我将其与Java一起使用),但作为依赖注入的粉丝,我也喜欢Spring,尤其是Spring通过仅使用@Value注释将配置注入对象的@Value

Therefore, I would love to know how to inject into an instance variable the value of a property using Play's built-in property resolution mechanism. 因此,我很想知道如何使用Play的内置属性解析机制将实例的值注入实例变量。 Something like this: 像这样:

@Component
public class SpringBeanWithinAPlay2Application {

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

Any clue anyone? 有任何线索吗? Many thanks in advance. 提前谢谢了。

I had the same problem a while ago and this was my way of making this work: 不久前我遇到了同样的问题,这是我完成这项工作的方式:

Firstly, when you boostrap your Spring Application context (I use annotation based configuration but the same should work for XML based), you have to add a custom PropertySource , which is the way Spring enables the addition of new way of resolving properties. 首先,当您增强Spring Application上下文时(我使用基于注释的配置,但对于基于XML的配置同样适用), 您必须添加一个自定义的PropertySource ,这是Spring启用添加新的解决属性方法的方式。 Something like this: 像这样:

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

The custom class PlayFrameworkPropertySource is the one that does the magic: 定制类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);
    }
}

In order for all this to work, you just need to do one more thing: explicitly declare a bean of type PropertySourcesPlaceholderConfigurer in some @Configuration class you might be using: 为了使所有这些工作正常,您只需要做一件事:在您可能使用的某些@Configuration类中显式声明一个PropertySourcesPlaceholderConfigurer类型的Bean

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

Important Note: this bean must be static , as it's a BeanFactoryPostProcessor and it should be loaded prior to any other regular @Bean. 重要说明:该bean必须是static ,因为它是BeanFactoryPostProcessor ,并且应在其他常规@Bean之前加载。

This worked like a charm for me, hope this is helpful to someone else! 这对我来说就像是一种魅力,希望对其他人有帮助!

Cheers, 干杯,
Jonathan 乔纳森

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM