我如何将一个spring bean注入一个休眠的SequenceGenerator

时间:2013-01-23 16:08:20

标签: spring hibernate

我有一个为hibernate编写的自定义SequenceGenerator:

public class LoginGenerator extends SequenceGenerator {

    @Autowired
    ITicketService ticketService;

    @Override
    public Serializable generate(SessionImplementor session, Object obj) {
        Ticket ticket = (Ticket) obj;
        Long maxCounterOfSection = ticketService.findMaxSectionCounter(ticket
            .getSection());
        maxCounterOfSection++;
        return ticket.getSection() + "-" + maxCounterOfSection;
    }
}

但是这个发电机里面没有弹簧背景! ticketService为null。我已经为我的生成器尝试了@Component注释,但没有成功。

PS:我使用spring 3.2.0-FINAL和hibernate 3.6.10-FINAL并且无法更新到hibernate4!

任何想法,任何人?

1 个答案:

答案 0 :(得分:2)

使用ApplicationContextAware类解决了问题,如上所述。

public class ApplicationContextProvider implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @SuppressWarnings("static-access")
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

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

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

applicationContext.xml我添加了<bean id="applicationContextProvider" class="de.gfz.rz.spring.ApplicationContextProvider"></bean>

这里的用法:

public class LoginGenerator extends SequenceGenerator {

    @Override
    public Serializable generate(SessionImplementor session, Object obj) {
        ITicketService ticketService = ApplicationContextProvider
            .getBean(ITicketService.class);
        Ticket ticket = (Ticket) obj;
        Long maxCounterOfSection = ticketService.findMaxSectionCounter(ticket
            .getSection());
        maxCounterOfSection++;
        return ticket.getSection() + "-" + maxCounterOfSection;
    }
}