2016-05-13 22 views
2

我想寫一個多租戶春季啓動應用程序,但其在服務器啓動時(即不是懶洋洋地,一旦承租人請求豆)我如何熱切地爲每個租戶初始化bean?

,支持多租戶,我創建了一個麻煩,渴望初始化豆@CustomerScoped基於ThreadLocal字符串值創建對象的註釋。

我的配置提供了這樣一個bean懶洋洋地初始化:

@Autowired 
private AutowireCapableBeanFactory beanFactory; 

@Bean 
@CustomerScoped 
public Scheduler getScheduler() { 
    CreateDefaults job = factory.createBean(CreateDefaults.class)); 
    Scheduler scheduler = new Scheduler(); 
    scheduler.schedule(job); 
    return scheduler; 
} 

@PostConstruct 
public void init() { 
    CustomerScope.setCustomer("tenant1"); 
    getScheduler(); 
    CustomerScope.setCustomer("tenant2"); 
    getScheduler(); 
    CustomerScope.clearCustomer(); 
} 

當啓動服務器時,應創建兩個調度,每個將執行自己的「創建默認值」的實例。 當租戶自己訪問應用程序時,他們應該獲得他們自己的此調度程序實例。 這似乎工作,但我想知道這是否是正確的做事方式。 特別是,我擔心beanFactory本身沒有作用域。

此方法適用於更復雜的系統嗎?

+1

工廠並不需要先限定,它只需要知道現有的範圍,以便它可以將bean的存儲/檢索委託給範圍。 – zapl

+0

我如何讓工廠意識到範圍?這是否足以在我的配置中? '@Bean public static CustomScopeConfigurer customScope(){ CustomScopeConfigurer configurer = new CustomScopeConfigurer(); configurer.addScope(CustomerScope.CUSTOMER_SCOPE_NAME,new CustomerScope()); return configurer; }' –

+0

是的,應該是這樣。配置器是一個*「簡單的'BeanFactoryPostProcessor'實現,它向包含'ConfigurableBeanFactory'的註冊自定義'Scope's。」* - 在spring-boot中'AutowireCapableBeanFactory' – zapl

回答

1

我的代碼示例實際上是正確的。 BeanFactory中並不需要先限定本身,它只是必須意識到範圍,這在我的情況下,可以在配置來實現的:

@Bean 
public static CustomScopeConfigurer customScope() { 
    CustomScopeConfigurer configurer = new CustomScopeConfigurer(); 
    configurer.addScope(CustomerScope.CUSTOMER_SCOPE_NAME, new CustomerScope()); 
    return configurer; 
}