Akshay Srivastava Akshay Srivastava - 1 year ago 63
Java Question

@Component annotation to be used with qualifier

Let's say I have a single class with


public class MyClass {}

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

  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:

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