2013-08-07 16 views
0

我有一些bussines類,它們注入了一些使用servlet請求範圍提供的依賴關係。使用請求範圍和線程注入

問題是,我想在某些超過servlet請求的線程中使用bussines類。 什麼是最透明的方式來做到這一點?

+0

Singleton不是一個選項。在部分我使用GUICE來避免單身人士。 – lujop

回答

0

如果您使用的是Spring(根據您使用的術語來描述您的問題,您似乎正在使用),則可以使用AOP scoped-proxy作爲請求範圍對象,然後將此代理注入超出servlet請求的對象。 scoped-proxy將負責在您每次訪問時使用正確的實例。

+0

不使用彈簧。 – lujop

+0

如果使用guice,你可以使用Provider來實現相同的功能,儘管多了一點與框架的耦合。請參閱https://code.google.com/p/google-guice/wiki/Scopes –

0

那麼, 我不知道如果我得到你的問題。我認爲這是與建築本身的問題,但卻能幫助您:

吉斯模塊

bind(Bussines.class).annotatedWith(Names.named("request")).to(Bussines.class).in(RequestScoped.class); 
bind(Bussines.class).annotatedWith(Names.named("session")).to(Bussines.class).in(SessionScoped.class); 
bind(Bussines.class).annotatedWith(Names.named("application")).to(Bussines.class).asEagerSingleton(); 

使用

@Inject @Named("request") 
    private Bussines bussines; //inject a new bussines class every request 

    @Inject @Named("session") 
    private Bussines bussines; //inject a new bussines class each session 
//This is little bit tricky, cuz Bussines is stored in session. In Stage.PRODUCTION are all injection created eagerly and there is no session at injection time. Session binding should be done in lazy way - inject provider and call bussinesProvider.get() when em is needed; 

    @Inject @Named("application") 
    private Bussines bussines; //inject singleton 

您也可以使用Private modules綁定不同範圍的對象到一個類。不要忘記揭露它。

0

我看到3個選項:

  • 你可以添加你需要的是有一個像應用程序或會話範圍
  • 更大範圍內你可以堅持在一個文件中的信息或數據庫中的對象的信息,看它以後
  • 你可以保存線程的信息,或使用一個線程範圍:http://code.google.com/p/google-guice/issues/detail?id=114
0

我可能不會建議你直接使用或注射的Http不在請求範圍內的業務bean的ServletRequest。因爲這會分解應用層。如果您想要請求或請求頭中的值,那麼您可以將值傳遞給對象以傳遞到業務層,否則它不安全,並且通常,應用程序將在該請求範圍內應用某個安全攔截器,但如果你直接注入到其他層,然後跳過,攔截器可能被跳過......這樣也破壞了封裝,明顯是反模式。