如何让Hibernate Cache使用的自定义RegionFactory具有Spring注入的bean?

brccelvz  于 2023-10-23  发布在  Spring
关注(0)|答案(2)|浏览(114)

我有课

public class SpringRedisRegionFactory extends RegionFactoryTemplate {

  @Autowired
  private transient RedisConnectionFactory redisConnectionFactory;

  @Override
  protected DomainDataStorageAccess createDomainDataStorageAccess(
      DomainDataRegionConfig regionConfig, DomainDataRegionBuildingContext buildingContext) {

    return registerNewStorageAccess(regionConfig.getRegionName());
  }
   ...

  private DomainDataStorageAccess registerNewStorageAccess(final String regionName) {

    if (storageAccesses == null) {
      throw new IllegalStateException("prepareForUse was not executed yet");
    }

    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); // does not seem to work
    final var storageAccess = new SpringRedisStorageAccess(regionName, redisConnectionFactory);
    storageAccesses.add(storageAccess);
    return storageAccess;
  }
}

我得到
当前WebApplicationContext不可用于处理SpringRedisRegionFactory:确保在Spring WebApplicationContext初始化后在Spring Web应用程序中构造此类。不注射。
我使用了一个类似的技术,但这似乎不适用于RegionFactory

62lalag4

62lalag41#

我知道Spring确实有RedisConnectionFactory,因为我可以自动连接它并查看值。问题是,当工厂类由Hibernate创建时,它可能不可用,也不在ManagedBeanRegistry中。
为了解决这个问题,我必须简单地在初始化时存储值。

@Configuration
@RequiredArgsConstructor
public class HibernateStorageConfiguration implements InitializingBean, DisposableBean {

  private static final AtomicReference<RedisConnectionFactory> configuredRedisConnectionFactoryRef =
      new AtomicReference<>();

  private final RedisConnectionFactory redisConnectionFactory;

  public static RedisConnectionFactory getConfiguredRedisConnectionFactory() {

    return configuredRedisConnectionFactoryRef.get();
  }

  @Override
  public void afterPropertiesSet() {

    configuredRedisConnectionFactoryRef.set(redisConnectionFactory);
  }

  @Override
  public void destroy() {

    configuredRedisConnectionFactoryRef.set(null);
  }
}
dl5txlt9

dl5txlt92#

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

我会想到这样的东西:

public class SpringRedisRegionFactory extends RegionFactoryTemplate {

    private transient RedisConnectionFactory redisConnectionFactory;

    @Override
    protected void prepareForUse(SessionFactoryOptions settings, Map configValues) {
        StandardServiceRegistry serviceRegistry = settings.getServiceRegistry();
        ManagedBeanRegistry beanRegistry = serviceRegistry.requireService(ManagedBeanRegistry.class);
        redisConnectionFactory = beanRegistry.getBean(RedisConnectionFactory.class);
    }

... 

}

相关问题