Sobes.tech
Middle

Mis juhtub, kui proovite saada sama bean'i ApplicationContextis?

sobes.tech AI

Vastus AI-lt

ApplicationContext by default will return a reference to the same bean instance, because the scope of beans by default in Spring is singleton.

If the bean is configured with another scope, for example prototype, then each request to the ApplicationContext will create and return a new bean instance.

Example of configuring a bean 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 the 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); // For singleton returns true, for prototype returns false

        context.close();
    }
}