Sobes.tech
Middle

O que acontece se tentar obter o mesmo bean no ApplicationContext?

sobes.tech IA

Resposta da IA

ApplicationContext devolverá uma referência ao mesmo bean por padrão, pois o escopo dos beans por padrão no Spring é singleton.

No caso de o bean estar configurado com outro escopo, por exemplo prototype, então a cada solicitação o ApplicationContext criará e retornará uma nova instância do bean.

Exemplo de configuração de um bean com escopo prototype:

@Configuration
public class AppConfig {

    @Bean
    @Scope("prototype") // Especificamos o escopo prototype
    public MyPrototypeBean myPrototypeBean() {
        return new MyPrototypeBean();
    }
}

Exemplo de obtenção de um bean do 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); // Para singleton retornará true, para prototype retornará false

        context.close();
    }
}