0 امتیاز
قبل در برنامه نویسی توسط (1.1هزار امتیاز)

چگونه می توان از Google Guice بعنوان ابزار Dependency Injection در Play Framework استفاده کرد؟

1 پاسخ

0 امتیاز
قبل توسط (1.1هزار امتیاز)

از Play Framework 2.4 که هنوز release نشده است، Google Guice بعنوان ابزار Dependency Injection پیشفرض Play Framework خواهد بود و نیازی به تنظیمات خاصی نخواهد بود. برای Play Framework 2.3 باید تنظیمات زیر را انجام دهید:

1- کتابخانه Google Guice را بعنوان dependency در فایل build.sbt اضاقه کنید:

libraryDependencies ++= Seq(
  javaJdbc,
  javaJpa,
  cache,
  javaWs,
  "com.google.inject" % "guice" % "3.0"
)

2- برای معرفی Action ها در فایل route از @ استفاده کنید.

GET     /                           @controllers.Application.index()

3- کلاس Global بصورت زیر در فولدر app برنامه ایجاد کنید:

import com.google.inject.AbstractModule;  
import com.google.inject.Guice;  
import com.google.inject.Injector;  
import play.Application;  
import play.GlobalSettings;  
import services.GreetingService;  
import services.RealGreetingService;
 
public class Global extends GlobalSettings {
 
    private Injector injector;
 
    @Override
    public void onStart(Application application) {
        injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                bind(GreetingService.class).to(RealGreetingService.class);
            }
        });
    }
 
    @Override
    public <T> T getControllerInstance(Class<T> aClass) throws Exception {
        return injector.getInstance(aClass);
    }
}

همانطور که مشاهده می کنید GreetingService که یک Interface می باشد به کلاسی که آن را پیاده سازی کرده است  bind شده است (RealGreetingService).

4- حالا می توانید با استفاده از @Inject از قابلیت Dependency Injection در پروژه خود استفاده کنید. برای مثال در کنترلر ها:

public class Application extends Controller {
 
    @Inject
    private GreetingService greetingService;
 
    public Result index() {
        return ok(index.render(greetingService.greeting()));
    }
 
}

سوالات مشابه

0 امتیاز
1 پاسخ 203 بازدید
+1 امتیاز
2 پاسخ 917 بازدید
0 امتیاز
1 پاسخ 1.1هزار بازدید
0 امتیاز
1 پاسخ 1.4هزار بازدید
...