如何在 Spring 启动期间生成 HttpServletRequest 以进行 bean 初始化?

发布于 2025-01-02 08:55:59 字数 373 浏览 0 评论 0原文

我想要一个 bean,它可以运行我们所有的 FreeMarker 模板,并为每个模板实例化一个 FreeMarkerView,以便预加载这些 bean。我还想做一些其他需要 HttpServletRequest 的类似优化。

所以我的问题是:Spring 中是否有任何正常的方法可以在应用程序启动期间在 Spring bean 上运行 init() 方法并为其提供某种 HttpServletRequest?我想避免模拟完整的 HttpServletRequest,并且我知道我总是可以设置一个控制器并打开一个套接字并向其发送请求,但我想知道是否有更好或更正常的方法来做到这一点。

当然,肯定还有其他人想要在启动时或计划任务等时设置 HttpServletRequest 而无需发出 HTTP 请求?

I'd like to have a bean that runs through all our FreeMarker templates and instantiates a FreeMarkerView for each one, so that the beans are preloaded. There've been a couple other similar optimisations that I'd like to do that require an HttpServletRequest.

So my question is this: is there any normal way in Spring to run an init() method on a Spring bean during the application startup and provide it with some sort of HttpServletRequest? I'd like to avoid mocking out a full HttpServletRequest, and I know I could always setup a controller and open a socket and send a request to it, but I wanted to know if there was any better or more normal way of doing it.

Surely there must be other people who've wanted to set up an HttpServletRequest without making an HTTP request, either at startup or on a scheduled task, etc.?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

永不分离 2025-01-09 08:55:59

当应用程序启动时,还没有 HTTP servlet 请求。事实上,Tomcat 在启动期间开始侦听和接受 8080 端口上的连接,但仅当所有应用程序都成功启动时才将它们传递给适当的 servlet。这意味着您不能在启动期间调用自己,因为这会导致死锁 - 您正在等待响应,而 Tomcat 正在等待您,而该响应会被阻止。

这也意味着在启动期间根本不可能获得任何 HTTP Servlet 请求(至少以 Tomcat 为例),因为还没有任何请求。是的,模拟是正确的方法,但恐怕如果这些库需要 HttpServletRequest 实例,简单的模拟可能还不够。

When the application is starting there are no HTTP servlet requests yet. In fact, Tomcat during bootup starts listening and accepting connections on 8080 port, but passes them to appropriate servlets only when all applications have successfully started. This means you cannot call yourself during startup since this will lead to deadlock - you are waiting for a response which is blocked by Tomcat that waits for you.

This also means that it is simply impossible (at least when Tomcat is taken as an exmaple) to obtain any HTTP servlet request during startup as there are absolutely no requests yet. Yes, mocking is the correct way, but I'm afraid if these libraries require an HttpServletRequest instance, simple mock might not be enough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文