我有一些bussines類,它們注入了一些使用servlet請求範圍提供的依賴關係。使用請求範圍和線程注入
問題是,我想在某些超過servlet請求的線程中使用bussines類。 什麼是最透明的方式來做到這一點?
我有一些bussines類,它們注入了一些使用servlet請求範圍提供的依賴關係。使用請求範圍和線程注入
問題是,我想在某些超過servlet請求的線程中使用bussines類。 什麼是最透明的方式來做到這一點?
如果您使用的是Spring(根據您使用的術語來描述您的問題,您似乎正在使用),則可以使用AOP scoped-proxy作爲請求範圍對象,然後將此代理注入超出servlet請求的對象。 scoped-proxy將負責在您每次訪問時使用正確的實例。
不使用彈簧。 – lujop
如果使用guice,你可以使用Provider來實現相同的功能,儘管多了一點與框架的耦合。請參閱https://code.google.com/p/google-guice/wiki/Scopes –
那麼, 我不知道如果我得到你的問題。我認爲這是與建築本身的問題,但卻能幫助您:
吉斯模塊
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綁定不同範圍的對象到一個類。不要忘記揭露它。
我看到3個選項:
我可能不會建議你直接使用或注射的Http不在請求範圍內的業務bean的ServletRequest。因爲這會分解應用層。如果您想要請求或請求頭中的值,那麼您可以將值傳遞給對象以傳遞到業務層,否則它不安全,並且通常,應用程序將在該請求範圍內應用某個安全攔截器,但如果你直接注入到其他層,然後跳過,攔截器可能被跳過......這樣也破壞了封裝,明顯是反模式。
Singleton不是一個選項。在部分我使用GUICE來避免單身人士。 – lujop