Amit Mahajan
Amit Mahajan

Reputation: 915

How to create a spring bean with specific number of maximum instances

I need to create a spring prototype bean in a server with limited RAM. One option is to use a spring bean which is a mix of Singleton and Prototype scopes, where i can specify maximum number of instances and threads.

Is there any way in Spring to create multi instance beans? If not how to we avoid out of memory errors when using spring prototype beans.

Upvotes: 0

Views: 1314

Answers (1)

Dmitrii N
Dmitrii N

Reputation: 360

If you really want to use spring for your purposes I would suggest using factory bean.

Your context:

<beans ...>
    <bean id="tool" class="com.example.ToolFactory"/>
</beans>

An example of a factory bean:

public class ToolFactory implements FactoryBean<Tool> {
    private AtomicInteger currentId = new AtomicInteger();

    @Override
    public Tool getObject() throws Exception {
        return new Tool(currentId.incrementAndGet());
    }

    @Override
    public Class<?> getObjectType() { return Tool.class; }

    @Override
    public boolean isSingleton() { return false; }
}

public class Tool {
    private final int id;
    public Tool(int id) { this.id = id; }
    public int getId() { return id; }
}

In Toolfactory.getObject() you can implement any logic you wish.
You can create a Pool of beans inside this factory.
Or you could throw an exception when bean count limit is reached.

How to use the Spring FactoryBean?
What's a FactoryBean?

Upvotes: 1

Related Questions