业务层使用@Context注解访问HttpServletRequest

2023-12-07

我可以在休息服务中使用 @Context 注释来访问 HttpServletRequest。但无法在存储库类中访问相同的内容。我不想在调用方法时将请求从 MyService 传递到 MyRespository 。

@Path("/someUrl")
public MyService{

@Context
private HttpServletRequest request;

@Get
public void someMethod()
{
   myRepository.someMethod();
}

}

但相同的注释不适用于我的存储库类

@Repository
public MyRepository
{

@Context
private HttpServletRequest request;

public void someMethod()
{
 //need request here
}
}

它注入空请求。不知道为什么这不起作用。


问题在于泽西岛(和itsDI框架HK2)是集成的,就是Spring组件可以注入Jersey(HK2)组件,但反之则不行。HttpServletRequest被绑定为 Jersey 组件。

您可以做的是创建一个 HK2 服务,它包装了 Spring 存储库,并且HttpServletRequest。 IMO,无论如何,这是更好的设计。存储库不应该关心HttpServletRequest,它只与数据有关。

所以你可以拥有

public class MyService {

    @Inject // or @Autowired (both work)
    private MyRepository repository;

    @Context
    private HttpServletRequest request;

}

然后将服务与HK2绑定

import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.process.internal.RequestScoped;

public class AppBinder extends AbstractBinder {

    @Override
    public void configure() {
        bindAsContract(MyService.class).in(RequestScoped.class);
        // note, if `MyService` is an interface, and you have 
        // an implementation, you should use the syntax
        //
        // bind(MyServiceImpl.class).to(MyService.class).in(...);
        //
        // Then you inject `MyService`. Whatever the `to(..)` is, 
        // that is what you can inject
    }
}

并在 Jersey 中注册活页夹

public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        register(new AppBinder());
    }
}

然后就可以注入了MyService进入您的资源类。

如果你不想走这条路,那么你需要做MyRepositoryHK2 服务,或使用 HK2Factory包装存储库,并显式注入它。就像是

import javax.inject.Inject;
import org.glassfish.hk2.api.Factory;
import org.glassfish.hk2.api.ServiceLocator;
import org.springframework.context.ApplicationContext;

public class MyRepositoryFactory implements Factory<MyRepository> {

    private final MyRepository repo;

    @Inject
    public MyRepositoryFactory(ApplicationContext ctx, ServiceLocator locator) {
        MyRepository r = ctx.getBean(MyRepository.class);
        locator.inject(r);
        this.repo = r;
    }


    @Override
    public MyRepository provide() {
        return repo;
    }

    @Override
    public void dispose(MyRepository t) {/* noop */}
}

然后注册工厂

@Override
public void configure() {
    bindFactory(MyRepositoryFactory.class).to(MyRepository.class).in(Singleton.class);
}

如果您执行上述操作,那么您只需使用MyRepository,而不是添加服务层。基本上,您需要从 Spring 获取存储库,并使用 HK2 显式注入它ServiceLocator(这是 Spring 的 HK2 类似物ApplicationContext).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

业务层使用@Context注解访问HttpServletRequest 的相关文章

随机推荐