0

I have visited intrview recently and was asked how to force spring create singleton bean several time.

As I understand properly it is possible if you have a several context but I don't understand mechanism.

Please explain it for me.

github example would be nice.

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

3 Answers3

3

You can inject multiple instances by declaring the bean multiple times with different @Qualifier:

@Configuration
public class YourConfiguration {

    @Bean
    @Qualifier("first")
    public Model firstInstance() {
        return new Model();
    }

    @Bean
    @Qualifier("second")
    public Model secondInstance(){
        return new Model();
    }
}

...

@Autowired
@Qualifier("first")
private Model first;

@Autowired
@Qualifier("second")
private Model second;
alexbt
  • 16,415
  • 6
  • 78
  • 87
  • it is different singletons of same type – gstackoverflow Jan 19 '17 at 10:50
  • It's one type, instantiated multiple times. Fits the bill in my opinion. Any potential solution will be "different singleton of the same type" wont it ? Anyway, it's your question, so you choose what you consider to be a good answer! – alexbt Jan 19 '17 at 10:52
  • @gstackoverflow The singleton is per bean, not per class (like the "classic" singleton pattern) – daniel gi Aug 24 '23 at 07:45
1

You can use @Qualifier to give a different name to your singleton-scoped bean and then simply autowired them.

@Component
@Qualifier(value ="first, second")
public class Scope {

}

@Component
public class MyClass {

    @Autowired
    private Scope first;

    @Autowired
    private Scope second;
}
0

There are different ways to have several copies of the same singleton bean, but you must provide Spring a way to differentiate them. IMHO the simplest way is to fully configure an parent bean, and then declare copies of it using the parent attribute.

This is in fact used to have several beans with same class and almost same configuration each specialized for example by a difference in an attribute. You only differentiate them by their name, and actually have to inject them by name.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252