How can I get the Hibernate Configuration object from Spring?
I am trying to obtain Spring-defined Hibernate Configuration and SessionFactory objects in my non-Spring code. The following is the definition in my applicationContext.xml file:
Code:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.cglib.use_reflection_optimizer">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.HashtableCacheProvider</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource"/>
</property>
</bean>
If I now call getBean("sessionFactory"), I am returned a $Proxy0 object which appears to be a proxy for the Hibernate SessionFactory object. But that isn't what I want - I need the LocalSessionFactoryBean itself because I need access to the Configuration as well as the S开发者_开发知识库essionFactory.
The reason I need the Configuration object is that our framework is able to use Hibernate's dynamic model to automatically insert mappings at runtime; this requires that we change the Configuration and rebuild the SessionFactory. Really, all we're trying to do is obtain the Hibernate config that already exists in Spring so that those of our customers that already have that information in Spring don't need to duplicate it into a hibernate.cfg.xml file in order to use our Hibernate features.
One obscure feature of the Spring container is the &
prefix:
When you need to ask a container for an actual
FactoryBean
instance itself, not the bean it produces, you preface the bean id with the ampersand symbol&
(without quotes) when calling thegetBean
method of theApplicationContext
. So for a givenFactoryBean
with an id ofmyBean
, invokinggetBean("myBean")
on the container returns the product of theFactoryBean
, and invokinggetBean("&myBean")
returns theFactoryBean
instance itself.
So in your case, using getBean("&sessionFactory")
should return you the LocalSessionFactoryBean
instance itself. Then you can call .getConfiguration()
to get the Configuration
object.
精彩评论