Play 2.5.3: Using dependency injection to get configuration values

前端 未结 5 1947
忘了有多久
忘了有多久 2021-02-05 22:59

I\'m trying to migrate a Playframework application from 2.4 to 2.5.3 and I have problems to get values from application.conf file:

Before t

相关标签:
5条回答
  • 2021-02-05 23:18

    you should try to remove private. use:

    @Inject Configuration configuration;
    

    instead of:

    @Inject private  Configuration configuration;
    
    0 讨论(0)
  • 2021-02-05 23:26

    Try with constructor injection instead:

    import javax.inject.Inject;
    import play.Configuration;
    import play.Logger;
    
    public class Zipper {
    
        private Configuration configuration;
    
        @Inject
        public Zipper(Configuration config) {
            this.configuration = config;
        }
    
        public void unZip(String zipFilePath) {
            Logger.debug("Display : zipFilePath"+zipFilePath);
            Logger.debug("before call parameter from application.conf");
            Logger.debug("configuration.getString = "+configuration.getString("Unzipedfile.path"));
            Logger.debug("aftercall parameter from application.conf");
        }
    }
    

    I'm not sure that Guice is capable of inject private fields. Anyway, constructor injection is the recommended injection type.

    0 讨论(0)
  • 2021-02-05 23:27

    I put here the answer, in order to help anyone with the same issue

    My error came from the way i used to instantiate my Zipper java class from my calling class.

    Thx to Igmar Palsenberg, he provided me the answer : https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!topic/play-framework/uLFqTM9_Iy4

    I used Zipper zipTest = new Zipper(); to instanciate my Zipper class and i have to use Zipper zipTest = injector.instanceOf(Zipper.class);

    0 讨论(0)
  • 2021-02-05 23:30

    Try to annotate your class with Singleton so that play can detect your bean to inject your resources.

    0 讨论(0)
  • 2021-02-05 23:32

    I think that you can initialize the configuration like this:

    private  Configuration configuration = Play.current().injector().instanceOf(Configuration .class);
    

    So, your Zipper will be:

    import javax.inject.Inject;
    import play.Configuration;
    import play.Logger;
    
    public class Zipper {
    
        private  Configuration configuration = Play.current().injector().instanceOf(Configuration .class);
    
        public void unZip(String zipFilePath) {
            Logger.debug("Display : zipFilePath"+zipFilePath);
            Logger.debug("before call parameter from application.conf");
            Logger.debug("configuration.getString = "+configuration.getString("Unzipedfile.path"));
            Logger.debug("aftercall parameter from application.conf");
        }
    }
    
    0 讨论(0)
提交回复
热议问题