2

We have an Object which does some calculations in a spring boot container. Lets call it "Sheet". We need to instantiate - let's say 10 - sheets when the application is started. Every time we start a calculation we need one instance of that sheet to be accessed via DI to be run in an extra Thread.

Any idea if that is possible in Spring?

Java_Waldi
  • 924
  • 2
  • 12
  • 29

1 Answers1

4

You can achieve this in the following way.. lets say that you have a Sheet class as follow. I have used java8 to compile the code.

Sheet.java

 @Component("sheet")
    @Scope(value = "prototype")
    public class Sheet {
        // Implementation goes here
    }

Now you need a second class SheetPool which holds 10 instances of Sheet

SheetPool.java

public class SheetPool {

    private List<Sheet> sheets;

    public List<Sheet> getSheets() {
        return sheets;
    }

    public Sheet getObject() {
        int index = ThreadLocalRandom.current().nextInt(sheets.size());
        return sheets.get(index);
    }

}

Note that SheetPool is not a Spring component. it is just a plain java class.

Now you need a third class which is a config class, which will take care of creating SpringPool object with 10 instance of Sheet

ApplicationConfig.java

@Configuration
public class ApplicationConfig {

@Autowired
ApplicationContext applicationContext;

@Bean
public SheetPool sheetPool() {
    SheetPool pool = new SheetPool();

    IntStream.range(0, 10).forEach(e -> {
        pool.getSheets().add((Sheet) applicationContext.getBean("sheet"));
    });

    return pool;
}

}

Now when the application starts SheetPool object will be create with 10 different instance of Sheet.. To access the Sheet object use the following code.

@Autowired
SheetPool  sheetPool;

Sheet sheetObj = sheetPool.getObject();
Jobin
  • 5,610
  • 5
  • 38
  • 53
  • 3
    This answer is correct, but note that if you make `SheetPool` implement [`FactoryBean`](https://docs.spring.io/spring/docs/5.2.2.RELEASE/javadoc-api/org/springframework/beans/factory/FactoryBean.html), then you can simply inject `Sheet` directly, and it will be retrieved from the factory bean (i.e. pool). – James_D Jan 04 '20 at 19:42