close nav

close nav

Thread: Spring Boot

Forum : Other Modules   21 Days ago
User Image
PrafulAgre

Newbie

Joined: 27 Dec, 2019

Points: 100

Threads: 1

Posts: 2

Spring Boot

| Quote Date : 20 Apr, 2021    Views:171    

How to call static method in Spring Boot?

Comments

User Image
arahul

Newbie

Joined : 30 Jul, 2019

Points : 100

Threads: 1

Posts: 3

Re: Spring Boot

Reply Date : 21 Apr, 2021

Hi,

what if you want to access a bean in a static method to perform some operation, since we can not access instance member in static method so for that we need to create a static member of type of that bean and assign injected bean to that static member and now we can use that value in static method and call it like normal static method, in below code snippet i have used constructor injection but we can use setter injection or postconstructor, idk i have answered your question correctly or not...



@Component
public class Robot {
    private static Sensor staticSensor; 
    private Sensor sensor;

    @Autowired
    public Robot(Sensor sensor) {
        this.sensor = sensor;
        Robot.staticSensor = sensor;
    }

    public static String getSensorType() {
        return staticSensor.getSensorType();
    }
}

?

User Image
PrafulAgre

Newbie

Joined : 27 Dec, 2019

Points : 100

Threads: 1

Posts: 2

Re: Spring Boot

Reply Date : 21 Apr, 2021

No, He didn't gave any scenario. 

"Ok.
Had he given any scenario to assume?
If not, I think his intention was different but didn't ask properly."

Replied by PIYUSH4169
User Image
PIYUSH4169

Newbie

Joined : 20 Apr, 2017

Points : 100

Threads: 6

Posts: 12

Re: Spring Boot

Reply Date : 21 Apr, 2021

Ok.
Had he given any scenario to assume?
If not, I think his intention was different but didn't ask properly.

I answered the same but interviewer didn't get satisfied. 

Replied by PrafulAgre
User Image
PrafulAgre

Newbie

Joined : 27 Dec, 2019

Points : 100

Threads: 1

Posts: 2

Re: Spring Boot

Reply Date : 21 Apr, 2021

I answered the same but interviewer didn't get satisfied. 

"Just like Java static method only. ClassName.methodName

"

Replied by PIYUSH4169
Load More

No More Comments