2017-06-06 186 views
0

我们有一个对象,它在弹簧引导容器中进行一些计算。让我们称之为“表”。我们需要实例化 - 比如在应用程序启动时使用10张纸。每次我们开始计算时,我们都需要通过DI访问该表的一个实例,以便在额外的线程中运行。Spring依赖注入对象池

任何想法,如果这是可能的春季?

+0

难道你不能使用一些常用的池吗?像https://commons.apache.org/proper/commons-pool/? – 2017-06-06 05:39:16

+1

创建自定义spring bean https://stackoverflow.com/a/15773000/6743203 –

回答

1

您可以通过以下方式实现此目的。假设您有一个Sheet类,如下所示。我用java8来编译代码。

Sheet.java

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

现在你需要一个第二类SheetPool持有的Sheet

10个实例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); 
    } 

} 

注意SheetPool不一个Spring组件。它只是一个普通的java类。

现在需要第三类是配置类,这将需要与Sheet

10实例创建SpringPool对象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; 
} 

}

的护理现在当应用程序启动SheetPool对象时将创建具有10个不同的工作表实例。要访问Sheet对象使用下面的代码。

@Autowired 
SheetPool sheetPool; 

Sheet sheetObj = sheetPool.getObject();