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();