Spring 管理HibernateSessionFactory
<bean id="hibernateTempalte" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="senssionFactory ' ref="sessionFactory''></property>
</bean>
@Component("userDao")
Public class UserDaoImpl implements UserDao{
Private HibernateTemplate;
@Resource
Public void setHibernateTemplate(HIbernateTemplate hibernateTemplate){
This.hibernateTemplate = hibernateTemplate;
}
// use hibernateTemplate in a method
hibernateTemplate.save(user);
hibernateTemplate.find(String HQL);
hibernateTemplate.findByCriteria(String sql);
HibernateTemplate.getSessionFactory.getCurrentSession();
}
@Resource
Public void setUserDao(UserDao userDao){
This.userDao = userDao;
}
Private UserManager um;
Public UserAction(){
ApplacationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
um = (UserManager)Ctx.getBean("UserManager");
}
Spring与Struts整合,由Spring负责管理所有Action的初始化
tomacat启动时初始化Spring中的bean对象,需要在web.xml中添加下面监听器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
<!-- Default: find WEB-INF/applicationContext.xml-->
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-*.xml, classpath*:applicationContext-*.xml</param-value>
<!-- customized config
<param-value>classpath:beans.xml</param-value>
-->
</context-param>
<action name="user" class="com.bjsxt.registration.action.UserAction">
<result name="success">/registerSuccess.jsp</result>
<result name="fail">/registerFail.jsp</result>
</action>
其中,@Component表示该类由Spring管理并且负责生成实例;@Resource 表示由Spring负责提供实例,不用手动new出来。