Changing scopes to @Component annotated class

In this post under Spring Core, I will show with example how to change the scope of class annotated with “@Component” annotation.

By default whenever we annotate a class with “@Component” annotation the scope of the bean is set to “singleton”.

We can change this by the help of “@Scope” annotation which is also applied at the class level.

Below is the example

Apple Class

1  package package13;
2
3 import org.springframework.context.annotation.Scope;
4 import org.springframework.stereotype.Component;
5
6 @Component
7 @Scope("prototype")
8 public class Apple {
9 public static int counter = 0;
10 public int id;
11
12 public Apple() {
13 Apple.counter = Apple.counter + 1;
14 id = Apple.counter;
15 }
16
17 @Override
18 public String toString() {
19 return "Apple Id: " + id;
20 }
21 }

In the above class, at line 6, as usual I annotated the class with “@Component” annotation.

Then at line 7, I annotated the class with “@Scope” annotation and passing the required scope as an argument, which in this case is “prototype”.

As a result whenever we say “getBean” a new object of “Apple” class is created.

In this way we can change the scope of class annotated with “@Component” annotation.

Leave a comment