Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何为每个租户初始化bean?_Java_Spring_Spring Boot - Fatal编程技术网

Java 如何为每个租户初始化bean?

Java 如何为每个租户初始化bean?,java,spring,spring-boot,Java,Spring,Spring Boot,我正在尝试编写一个多租户Spring引导应用程序,但在服务器启动时很难初始化bean(即,租户请求bean时不会延迟) 为了支持多租户,我创建了一个@CustomerScoped注释,该注释基于ThreadLocal字符串值创建对象 我的配置提供了这样一个bean,并对其进行惰性初始化: @Autowired private AutowireCapableBeanFactory beanFactory; @Bean @CustomerScoped public Scheduler getSch

我正在尝试编写一个多租户Spring引导应用程序,但在服务器启动时很难初始化bean(即,租户请求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本身没有确定范围


这种方法是否适用于更复杂的系统?我的代码示例实际上是正确的。 Beanfactory本身不需要确定作用域,它只需要知道作用域,在我的情况下,这可以通过配置实现:

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

工厂不需要确定作用域,它只需要知道现有的作用域,这样它就可以将bean的存储/检索委托给作用域。如何让工厂知道作用域?在我的配置中有这个就足够了吗<代码>@Bean public static CustomScopeConfigurer customScope(){CustomScopeConfigurer configurer=new CustomScopeConfigurer();configurer.addScope(CustomerScope.CUSTOMER_SCOPE_NAME,new CustomerScope());return configurer;}应该是。configurer是一种“简单的
BeanFactory后处理器
实现,它使用包含
ConfigurableBeanFactory
”的
AutowireCapableBeanFactory
注册自定义
范围
”—在spring boot中,AutowireCapableBeanFactory谢谢,您愿意将其表述为一个答案吗?我很乐意把它标记为“答案”。