最近在跟老狼做一个项目,框架用的是Spring MVC+Hibernate,大多使用注解方式(如:[Annotation方式实现AOP])进行的配置。
因为框架全都使用的是最新版本,所以遇到个问题:
在applicationContext.xml中对DAO的配置是这样的:
1 | <bean id="baseAdminDAO" class="com.ineeke.database.BaseAdminDAO" /> |
而我一直都是这么配置的:
1 2 3 | <bean id="baseAdminDAO" class="com.ineeke.database.BaseAdminDAO"> <property name="sessionFactory" ref="sessionFactory" /> </bean> |
很奇怪的是,第一种配置方式的程序竟然跑起来没有问题,可是明明没有注入sessionFactory啊,为什么没问题呢?
后来在hibernate.xml中看到如下一段关于sessionFactory的配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.current_session_context_class">thread</prop> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">false</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop> </props> </property> <property name="packagesToScan"> <list> <value>com.ineeke.database</value> </list> </property> </bean> |
原来新版本的Spring会自动扫描packagesToScan所指定的包下面的DAO并注入sessionFactory。这可真是方便多了,不再需要给每个DAO一个一个的注入了。

