Home > Mobile >  @Component with request scope attributes
@Component with request scope attributes

Time:12-08

I have a class in my SpringBoot project with @Component. By default, the Scope of this is singleton and it's OK.
But now I need an object, with request scope, that will be used in many methods of this Component class. The only way to do this is passing this object as parameter in all methods? Or can I, for example, declare a @RequestScope attribute in a singleton, or something like that?

----EDIT

An example:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    @Autowired
    private MyBC myBC;

    private MyClass myObject;

    public method1(MyClass param) {
        myObject = param;
        method2();
    }

    public method2() {
        System.out.println(myObject);
    }
}

My problem is: in this code, myObject is a singleton. Depending on concurrency, I will have problems with different requests, one will affect the other in method2(). I need myObject to be Request Scoped.

CodePudding user response:

Doesn't seem clean to me:

Firstly, let's call your @Component class as a Component.


Do you want to use another singleton object ( call it OtherS) inside your Component's methods?

Use Lombok's RequiredArgsConstructor with private static final OtherS otherSingleton, then you can use it inside your Component, in any methods.


OR


Do you want to use Component's object in other methods of other class?

You can inverse previous block and make same thing with Component (as with OtherS earlier). As you declare it as a Bean inside another Bean using @RequiredArgsConstructor it will not be null and will be used as a Singleton class attribute (so you can access it with this-kw).

CodePudding user response:

You can define MyClass as a @RequestScope component as follows:

@Component
@RequestScope
public class MyClass {

  private Object data;

  public MyClass(HttpServletRequest request) {
    data = //extract data from the request
  }

  public Object getData() {
    return data;
  }
}

Then you inject it like any other bean and don't have to pass the MyClass parameter to each method. The component is instantiated by each request only if you access it, as described here.

Beware that the request scope is not available outside a thread attached to a request. If you access it from a non-request-bound thread the following exception will be thrown:

java.lang.IllegalStateException: No thread-bound request found

  • Related