Akshay Srivastava Akshay Srivastava - 5 months ago 15
Java Question

@Component annotation to be used with qualifier

Let's say I have a single class with

@Component
annotation

@Component
public class MyClass {}


Now I wanna use it with two different scopes:
prototype
and
singleton
without defining it in configuration.
Is that possible?

Answer
  1. There should never be a use case for having the same bean in two different scopes. It's a huge architectural smell and you should probably redesign your application.

  2. That said, perhaps you mean you need to inject a prototype-scoped bean into a singleton bean? That's a common use case and the implications are adressed in these manual sections:

  3. But if you do insist to have the same bean in two different scopes, that can be achieved by using @Bean methods:

    @Configuration
    public class MyConfig{
        @Bean public MyClass singletonScope(){ return new MyClass(); }
        @Bean @Scope("prototype") public MyClass prototypeScope(){ return new MyClass(); }
    }
    
Comments