문제

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);
}
도움이 되었습니까?

해결책

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");

다른 팁

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");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top