Member-only story
Spring @Bean annotation and anonymous object in java
I got confused with the concept of anonymous inner class and @Bean annotation which is used in the spring. The question is that when we use the @Bean annotation we explicitly return an object and it doesnot have any reference to it. Is this returning bean an anonymous object?
@Bean public MyService myService() { return new MyServiceImpl(); }
Here we are returning the object of MyServiceImpl and we donot have the reference for it so is it anonymous object. Anonymous object, anonymous inner class, and Spring’s @Bean annotation seem similar, but they are conceptually quite different.
An anonymous object is simply an object created without assigning it to a variable.
new MyServiceImpl().performTask();
Here we created an object using new MyServiceImpl() but we didn’t store it in a variable like.
MyServiceImpl obj = new MyServiceImpl();
It’s a one-time-use object and we can’t reuse it because we have no reference to it so this makes it as an anonymous object, not to be confused with an anonymous class.
An anonymous inner class is a class without a name defined inside another class, often used for short, one-off implementations (typically for interface or abstract class implementations).
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Running in thread");
}
};
new…