I need to update the Spring bean scope so that older data is not processed along with new data. Let’s say we have a list managed by an object called Obj1. We add an item to the list, such as “Hi”. Later, another object called Obj2 adds a new item to the same list, like “Hello”. When we print the method using Obj1, it should display “Hi”. However, when we call the print method using Obj2, it should only print its added value, which is “Hello”
my Singleton Class :
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class SingletonBean {
private List<String> list;
public SingletonBean(List<String> list) {
this.list = new ArrayList<String>();
System.out.println("Singleton Bean");
}
public void process(String str) {
list.add(str);
//this will add new element in the same list and print with previous value as well
}
public void print() {
System.out.println(list);
}
}
Main class from where we call the singletonBean1 and SingletonBean2 object to add the item into the List
@SpringBootApplication
public class DemoRestApiApplication {
public static void main(String[] args) {
var context = SpringApplication.run(DemoRestApiApplication.class, args);
SingletonBean singletonBean1 = context.getBean(SingletonBean.class);
SingletonBean singletonBean2 = context.getBean(SingletonBean.class);
singletonBean1.process("Hi");
singletonBean1.print();
singletonBean2.process("Hello");
singletonBean2.print();
}
}
My Expected Result should be
[Hi]
[Hello}
Current Result is
[Hi]
[Hi, Hello]
kindly suggest some technicaly feasible implementation which should not break my singleton class structure