关于Spring与hibernate整合的困惑

在整合Spring和Hibernate的过程中遇到一点问题。不太明白Spring是怎样将SessionFactory实例化的,我的applicationContext.xml如下配置


    <context:component-scan base-package="com.bjwl">context:component-scan>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource">property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">trueprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop>
            props>
        property>
        <property name="mappingLocations">
            <list>
                <value>classpath:com/bjwl/domain/*.hbm.xmlvalue>
            list>
        property>
    bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory">property>
    bean>


    
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory">property>
    bean>
    <tx:annotation-driven transaction-manager="transactionManager"/>

public class HibernateTest {
    //ApplicationContext ac =  new ClassPathXmlApplicationContext("applicationContext.xml");
    @Resource
    private SessionFactory sessionFactory;

    public void test1(){
        //SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");(可以获取到sessionFactory)
        System.out.println(sessionFactory);//(输出为null,也就是sessionFactory没有注入)

    }
}

但是我改变了测试方法如下:

@Service
public class UserService {

    @Resource
    private SessionFactory sessionFactory;

    @Transactional
    public void saveTwoUsers() {
        Session session = sessionFactory.getCurrentSession();

        session.save(new Person());
        // int a = 1 / 0; // 这行会抛异常
        session.save(new Person());
    }
}

@Test
        public void testTransaction() throws Exception {
            UserService userService = (UserService) ac.getBean("userService");
            userService.saveTwoUsers();
        }

这样又能够执行成功。sessionFactory注入成功。不清楚为什么会有这两种结果。希望能有高手能帮我解惑。

你可能感兴趣的:(框架)