Spring MVC:HttpSession的自动装配如何工作? [英] Spring MVC: How autowiring of HttpSession works?

查看:122
本文介绍了Spring MVC:HttpSession的自动装配如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道HttpSession的自动装配如何工作.

I would like to know how autowiring of HttpSession works.

如果我们这样声明:

@Autowired 
private HttpSession httpSession;

完全在Spring工作流程中时,上面声明的httpSession变量将使用request.getSession(true)初始化吗?

When exactly in the Spring workflow, httpSession variable declared above will be initialized with request.getSession(true)?

推荐答案

我不明白为什么要自动连接HttpSession,但这是自动装配的工作原理.

I don't understand why you want to autowire HttpSession but here is how autowiring works.

要自动装配一个类,您需要通过使用批注(@ Controller,@ Service,@ Repository,@ Component)或在配置类中声明@Bean来将其指定为Bean.定义bean后,Spring上下文初始化时(在启动Webapp的服务器期间,在控制台/独立应用程序的情况下显式初始化spring上下文),Spring会自动装配或构造对象.

To Autowire a class you need to specify it as a bean either by using annotations (@Controller, @Service, @Repository, @Component) or by declaring @Bean in config class. Once you define a bean Spring autowires or constructs the objects when the spring context initializes (during server startup for webapp and you explicitly initialize spring context in case console/standalone app).

由于只能从HttpServletRequest对象获取HttpSession,因此您无法在应用程序启动期间对其进行初始化,因为启动期间没有HttpServletRequest.如果您希望在获取HttpSession之前实现一些逻辑,则可以创建一个像这样的util方法

Since HttpSession can only be fetched from HttpServletRequest object, you cannot initialize it during application startup because there is no HttpServletRequest during startup. If you want some logic to implement before fetching the HttpSession you can create a util method like this

public getHttpSession(HttpServletRequest request) {
    // put your logic here and return session object 
}

这篇关于Spring MVC:HttpSession的自动装配如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆