Sobes.tech
Junior — Middle

How can a counter be implemented inside a method that tracks the number of calls to this method within a Spring component?

sobes.tech AI

Answer from AI

In a Spring component, you can implement a method call counter using a class field that increments with each call. For example, declare a field private int counter = 0; and in the method, do counter++.

Example:

@Component
public class MyComponent {
    private int counter = 0;

    public void myMethod() {
        counter++;
        System.out.println("Method called " + counter + " times");
        // rest of the method code
    }
}

It is important that the component is a singleton (by default in Spring) so that the field retains its state between calls. If the component is prototype-scoped, the counter will reset.

For thread safety, you can use AtomicInteger instead of int.

How can a counter be implemented inside a method that… - sobes.tech