Question

my java project with spring and hibernate,can't get the sessionFactory.it's null all the time when i use it. the configuration:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource">
        <ref bean="dataSource" />
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">
                org.hibernate.dialect.Oracle9Dialect
            </prop>
        </props>
    </property>
</bean>

<bean id="test" class="test.Test">
    <property name="sessionFactory" ref="sessionFactory"></property>
</bean>`

the main code of Test.java is

        private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public SessionFactory getSessionFacoty(){
        return this.sessionFactory;
    }
        public static void main(String[] args) {
    // TODO Auto-generated method stub
    Test test = new Test();
    System.out.println(test.sessionFactory);
}
Was it helpful?

Solution

Your test in the main method doesn't actually use Spring for injection. You need to load the applicationContext.xml then get the test bean from that.

So you could do something like this in your main:

ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});

Test test = (Test)context.getBean("test");

OTHER TIPS

You need to get Test object from spring context as well. Load your config xml and create the context and get the object from the context

eg.

Test test = (Test) context.getBean("test");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top