Issue
im currently struggling to understand beans in Spring. I try to understand Beans through a scenario that currently occured in my project. I have a Spring application in a Docker container. During the start up my application should build a heavy instance that takes long time to create. Now, My application is through a Message Queue connected. Every time my application get a message, it should use my heavy instance to proceed with the message.
I understand that a Spring bean per default a Singleton is and without any configuration it is not possible to create another instance. Spring will always use the first instance by first call.
Now i want to create a custome class who hold the object. aObject was during the start up created and has all information what I need. If I update now my aObject with updateAObject(). Will it change my aObject to the new value for all classes that use my CustomeA class? Do I need to handle concurrency problems?
I wrote a Junittest but I cant confirm if my solution is -ok-
Sorry for my not so good english. I try to get better.
@Component
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
public class CustomeA {
private ClassA aObject;
public ClassA() {
this.aObject = createHeavyCostInstance();
}
public ClassA createHeavyCostInstance() {
// do something here that takes long time to do
return object;
};
public ClassA updateAObject() {
this.aObject = update();
}
// Getter and Setter
}
@Configuration
@ComponentScan("com.package.config.dummy")
public class AppConfig {
}
//TestClass
@Test
public void testConfig() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
ClassA classA = context.getBean(ClassA.class);
classA.getAObject();
classA.setAObject(new Object());
ClassA classA_two = context.getBean(classA.class);
classA_two.getAObject();
context.close();
}
Solution
You're reassigning aObject
inside CustomeA.updateAObject
. Any class outside CustomeA
still has the older reference, not the newer reference. Instead, you should modify CustomeA.updateAObject
so that the attributes of the object corresponding to the reference aObject
are getting updated. This way, all classes with the aObject
reference can see the updated object that corresponds to the aObject
reference.
Your confusion is because you don't understand that difference between an object and a reference to an object. aObject
is a reference to the underlying object. aObject
is not an object.
Answered By - Dhruv Gairola