Sobes.tech
Middle

What happens if you try to get the same bean in ApplicationContext?

sobes.tech AI

Answer from AI

ApplicationContext by default returns a reference to the same bean instance, as the default scope of beans in Spring is singleton.

If a bean is configured with a different scope, such as prototype, then each request to the ApplicationContext will create and return a new bean instance.

Example of a bean configuration with prototype scope:

@Configuration
public class AppConfig {

    @Bean
    @Scope("prototype") // Specify the scope as prototype
    public MyPrototypeBean myPrototypeBean() {
        return new MyPrototypeBean();
    }
}

Example of obtaining a bean from ApplicationContext:

public class Main {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        MyPrototypeBean bean1 = context.getBean(MyPrototypeBean.class);
        MyPrototypeBean bean2 = context.getBean(MyPrototypeBean.class);

        System.out.println(bean1 == bean2); // Returns true for singleton, false for prototype

        context.close();
    }
}
What happens if you try to get the same bean in… - sobes.tech