1

我有一个为休眠编写的自定义 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;
    }
}

但是我在这个生成器中没有弹簧上下文!票务服务为空。我已经为我的生成器尝试了@Component 注释,但没有成功。

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

任何想法,任何人?

4

1 回答 1

3

如上所述,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;
    }
}
于 2013-01-23T23:39:04.557 回答