使用请求范围和线程进行注入

问题描述 投票:0回答:4

我有一些bussines类,它们注入了一些使用servlet请求范围提供的依赖项。

问题是我想在一些比servlet请求更长的线程中使用那些bussines类。什么是最透明的方式呢?

java guice guice-servlet
4个回答
0
投票

如果您正在使用Spring(根据您用来描述问题的术语,您似乎正在使用它),您可以为请求范围的对象使用AOP作用域代理,并将此代理注入到比servlet请求。 scoped-proxy将在您每次访问时使用正确的实例。


0
投票

好吧,我不确定我是否得到你的问题。我认为架构本身存在问题,但是这可以帮助您:

Guice模块

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个选项:


0
投票

我可能不会建议您直接在不在请求范围内的业务bean中使用或注入HttpServletRequest。因为这会打破app层。如果你想要请求或请求头中的值,那么你可以将值传递给对象以传递给业务层,因为否则,它是不安全的,通常,app会在该请求范围应用一些安全拦截器,但是如果你直接注入到其他层,然后它跳过,拦截器可能被跳过...这种方式也打破了封装,显然是反模式。

© www.soinside.com 2019 - 2024. All rights reserved.