Search code examples
javaspringspring-bootspring-bean

Prototype bean injection using type


I am new to spring world. While learning about Prototype bean, I came across a weird response.

  • I defined a bean with scope prototype
@Configuration
public class BeanConfiguration {

    @Bean
    @Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
    public MessageService configureEmailMessageService() {
        return new EmailMessageService();
    }
}
  • I am injecting the bean using Match By Type.
public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfiguration.class);
        MessageService email = context.getBean(EmailMessageService.class);
        System.out.println(email.hashCode());
    }

While executing this, I am getting

No qualifying bean of type 'com.my.personal.project.spring.di.bean.services.EmailMessageService' available

But when I inject using name as shown below, it's working.

MessageService email = context.getBean("configureEmailMessageService");

My question is : Isn't it possible to inject prototype bean through Type ? Or am I missing something ?

Thanks


Solution

  • You are searching for a bean of type EmailMessageService, but in the BeanConfiguration class you are exposing a method that return a generic MessageService.

    You need to get a bean (with the method getBean) that is a MessageService.class.

    Try to change the signature of method

    @Bean
    @Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
    public MessageService configureEmailMessageService() {
        return new EmailMessageService();
    }
    

    to

    @Bean
    @Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
    public EmailMessageService configureEmailMessageService() {
        return new EmailMessageService();
    }
    

    or change the row

    MessageService email = context.getBean(EmailMessageService.class);
    

    in

    MessageService email = context.getBean(MessageService.class);