简体   繁体   中英

Create n instances of bean in spring

I got a question in one of interview to create only n (Fixed number) instance of any bean. If more than n instances are tried to create at runtime then throw any exception or print a message. Thank in advance

Its easy to control over object creation of beans by providing custom bean factory. Where you can configure restriction like fixed number of object creation.

Example Code.

You just need to manage how many instances are created, you can do this in same bean using a list and a not standard constructor, but I will use a factory pattern:

Gived this bean

class BeanTest {
    String name;

    protected BeanTest(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return this.name;
    }

}

You create a Factory like this (in same package!)

class BeanFactory {
    private static final int LIMIT = 5;
    private static List<BeanTest> list = new ArrayList<BeanTest>();

    public static synchronized BeanTest getInstance(String name) {
        if (list.size() < LIMIT) {
            BeanTest beanTest = new BeanTest(name);
            list.add(beanTest);
            return beanTest;
        }
        System.out.println("Not giving instance");
        return null;
    }

}

Test:

public static void main(String[] args) {
    BeanTest a1 = BeanFactory.getInstance("a1");
    System.out.println(a1);
    BeanTest a2 = BeanFactory.getInstance("a2");
    System.out.println(a2);
    BeanTest a3 = BeanFactory.getInstance("a3");
    System.out.println(a3);
    BeanTest a4 = BeanFactory.getInstance("a4");
    System.out.println(a4);
    BeanTest a5 = BeanFactory.getInstance("a5");
    System.out.println(a5);
    BeanTest a6 = BeanFactory.getInstance("a6");
    System.out.println(a6);
}

OUTPUT:

a1
a2
a3
a4
a5
Not giving instance
null

NOTES:

  • If you need more security just add getInstance method of the bean constructor into the BeanTest class itself and make constructor private instead of protected
  • You can also make a method destroyInstance or removeInstance in order to make more dynamic the Factory :

     public static synchronized boolean removeInstance(BeanTest toRemove) { if (list.contains(toRemove)) { return list.remove(toRemove); } return false; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM