1

I have a requirement - where we use the HttpServletRequest request object to set the UserSession Details in this Object.

The UserSession are required to be fetched at various point in the Spring Application as per need and to access this, I Autowired the HttpServletRequest object. I used in multiple locations and it worked like a charm.

But the problem is, when I tried to use it in a Static contect, this request object throws compilation error "non-static variable . . . cannot be referenced from a static context" .

So, when I tried to make the HttpServletRequest as static, this turns out to be null. I am not sure why this happens and require a suitable solution to use in the static methods.

POJO Class

 public class POJOClass{

 @Autowired
 private HttpServletRequest request;

 public static String getData(){

    UserObject uObj = UtilService.getUser(request);
    //Throws Compilation error for request object.

 }

*Here UtilService is the class defined from which the UserSession is fetched.

Ashfaque Rifaye
  • 1,041
  • 3
  • 13
  • 22
  • i am reopening this because it is about using an injected object that is specific to a request. following the advice in the linked question will not be helpful. – Nathan Hughes Dec 29 '20 at 15:02

1 Answers1

3

You should manage your utility class in Spring,

Follow How to Autowire bean in a static class by adding static Initializer which will add using Configuration your class:

@Component
public class StaticContextInitializer { 
@Autowired
private MyConfig myConfig; 
@Autowired
private ApplicationContext context; 
@PostConstruct
public void init() {
   StaticUtils.setMyConfig(myConfig);
 }
}

Notice author warning of this usage

wiring a bean into a static class is strongly discouraged. This article is for those who insist on taking going ahead with it and are aware of what they are doing.

Ori Marko
  • 56,308
  • 23
  • 131
  • 233