How to get beans in a hibernate identifier generator?

时间:2019-03-06 11:33:08

标签: java spring hibernate

My application use the Spring and hibernate.

Gotta get the MyService bean in the IdentifierGenerator.

Example:

public class MyGenerator implements org.hibernate.id.IdentifierGenerator, org.hibernate.id.Configurable {

    @Autowired // doesn't work :(
    private MyService myService;

    @Override
    public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
    }

    @Override
    public Serializable generate(SessionImplementor sessionImplementor, Object obj) {
        ...

1 个答案:

答案 0 :(得分:1)

如果确实需要,您可以定义ApplicationContextHolder utility class并将其用于存储Spring上下文:

@Component
public class ApplicationContextHolder implements ApplicationContextAware {

  private static ApplicationContext applicationContext;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    synchronized (this) {
        if (ApplicationContextHolder.applicationContext == null) {
            ApplicationContextHolder.applicationContext = applicationContext;
        }
    }
  }

  public static <T> T getBean(Class<T> clazz) {
    return applicationContext.getBean(clazz);
  }

  public static <T> T getBean(String qualifier, Class<T> clazz) {
    return applicationContext.getBean(qualifier, clazz);
  }

然后使用静态方法获取MyService bean:

public class MyGenerator implements IdentifierGenerator, Configurable {

  @Override
  public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
    MyService service = ApplicationContextHolder.getBean(MyService.class);
  }

}

这违背了依赖注入的原理,但是有时候如果某些对象不是由Spring管理的,那就没有更好的方法了。