Spring/Boot Interview Questions

Prototype bean inside a singleton bean

@Test
    void getBlog() {
        Blog blogInstance1 = applicationContext.getBean("blog3", Blog.class);
        Blog blogInstance2 = applicationContext.getBean("blog3", Blog.class);
        assertThat(blogInstance1.equals(to(blogInstance2)));
        Author authorInstance1 = blogInstance1.getAuthor();
        Author authorInstance2 = blogInstance2.getAuthor();
        assertThat(authorInstance1.equals(to(authorInstance2)));
    }

Author(Prototype) is present inside Blog(singleton).On execution, this test case passes.

You might be expecting the second assertion to fail. Because Author being a prototype, Spring should have created two different bean instances.

So why does the equality assertion passes?

This is known as the scoped bean injection problem. In Spring, dependencies are resolved at instantiation time. This means when you autowire the Author prototype-scoped bean into the Blog singleton-scoped bean, Spring will:

  1. Instantiate a brand new Author prototype bean.
  2. Inject the Author instance into the singleton Blog bean. That exact same Author instance will be the sole instance that is ever supplied to the Blog bean

https://springframework.guru/spring-bean-scopes/

byteprogramming-o-0-1. jar —executable jar

byteprogramming-o-0-1.original. jar —Non- executable jar

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website at WordPress.com
Get started
%d bloggers like this: