-->

Spring MVC: How autowiring of HttpSession works?

2019-04-17 14:52发布

问题:

I would like to know how autowiring of HttpSession works.

If we declare like below:

@Autowired 
private HttpSession httpSession;

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

回答1:

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

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).

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 
}