79620433

Date: 2025-05-13 21:25:41
Score: 0.5
Natty:
Report link

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.

eg.

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).

eg.

Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("Running in thread");
    }
};
new Thread(r).start();

The new Runnable() { ... } is an anonymous inner class we are creating a new unnamed class that implements Runnable. It’s different from an anonymous object, though both concepts look similar.

Now, with your question:

@Bean
public MyService myService() {
    return new MyServiceImpl();
}

You are not creating an anonymous object in the usual Java sense though you don’t assign it to a variable in your method because Spring assigns and manages the object internally in the ApplicationContext.The return value new MyServiceImpl() is stored in a container-managed singleton (by default). You can later autowire it or retrievable using its bean name (usually the method name myService). So, even though you don't assign it a reference manually, Spring does assign and manage a reference. Therefore, the object is stored, managed, and reused unlike a true Java anonymous object.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Bean
  • Low reputation (1):
Posted by: Naman Madharia