quartz 中 使用 applicationContext.xml中的bean 得到 hiberante的Session

applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:jee="http://www.springframework.org/schema/jee" 
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
					http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
					http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
					http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
	default-lazy-init="true">

	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    	<property name="location">
    		<value>classpath:jdbc.properties</value>
		</property>
	</bean>	
	<bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource">		
		<property name="driver" value="${db.driver}"/>
		<property name="driverUrl" value="${db.url}"/>
		<property name="user" value="${db.user}"/>
		<property name="password" value="${db.password}"/>
    	<property name="alias" value="${db.alias}"/>
    	<property name="houseKeepingTestSql" value="${db.houseKeepingTestSql}"/>
    	<property name="maximumConnectionCount" value="${db.maximumConnectionCount}"/>
    	<property name="minimumConnectionCount" value="${db.minimumConnectionCount}"/>
	</bean>

	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">   
        <!-- 引用数据源 -->
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>                 
        <property name="annotatedClasses">   
            <list>   
            	<value>com.cal.entity.Bonetest</value>
            	<value>com.cal.entity.Calciumcal</value>
            	<value>com.cal.entity.Child</value>
                <value>com.cal.entity.City</value>
                <value>com.cal.entity.District</value>
                <value>com.cal.entity.Province</value>
                <value>com.cal.entity.Staturetest</value>
                <value>com.cal.entity.Userinfo</value>
                <value>com.cal.entity.Event21</value>
            </list>   
        </property> 
        <property name="hibernateProperties">   
            <props>   
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>   
                <prop key="connection.useUnicode">true</prop>
                <prop key="connection.characterEncoding">UTF-8</prop>
                <prop key="hibernate.show_sql">false</prop>   
                <prop key="hibernate.format_sql">false</prop>            
                <prop key="hibernate.jdbc.fetch_size">20</prop> 
                <prop key="hibernate.query.substitutions">true 1, false 0</prop> 
                <prop key="hibernate.jdbc.batch_size">20</prop>  
                <prop key="hibernate.cache.use_structured_entries">true</prop>
                <prop key="hibernate.cache.use_second_level_cache">true</prop> 
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path"></prop>                                    
            </props>   
         </property>               
    </bean>   
	
	<!-- 事务配置 -->
	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
	<context:annotation-config/> 
	<context:component-scan base-package="com.cal" />
	
	<!-- 使用annotation定义事务 -->
	<tx:annotation-driven transaction-manager="txManager" />
	
	<!-- 这里是spring 和  quartz 整合  start  -->
<bean id="quartzJob" class="com.cal.quartz.Edm" >
        <!-- 测试引用 -->
        <property name="aaa">
            <value>111</value>
        </property> 
    </bean> 
    
    <!-- 这里需要 spring-context-support.jar 不然抛找不到这个类异常 -->
    <bean id="jobtask"
        class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <ref bean="quartzJob" />
        </property>
        <property name="targetMethod">
            <value>edmSendEmail</value>
        </property>
    </bean>
    <bean id="doTime" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail">
            <ref bean="jobtask" />
        </property>
        <property name="cronExpression">
            <value>00 53 11 * * ? *</value>
        </property>
    </bean>
<!-- lazy-init="false" 容器启动就绑定?是这说法? -->
    <bean id="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> 
        <property name="triggers"> 
            <list> 
                <ref bean="doTime"/> 
            </list> 
        </property> 
    </bean> 

<!-- 这里是spring 和  quartz 整合  end  -->
	</beans>




AppContext 类:
存放servletContext 和 applicationContext  的类,然后在servlet中把两个context传入它的静态属性中,注意: servlet 必须 容器启动时就启动

package com.cal.utils;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;


public class AppContext {
	private final static AppContext instance = new AppContext();
	private ServletContext sc;
	private ApplicationContext ac;

	private AppContext() {
	}

	public static AppContext getInstance() {
		return instance;
	}


	public synchronized void setServletContext(ServletContext sc) {
		this.sc = sc;
	}

	public ServletContext getServletContext() {
		return sc;
	}
	
	public synchronized void setApplicationContext(ApplicationContext ac) {
		this.ac = ac;
	}

	public ApplicationContext getApplicationContext() {
		return ac;
	}
	
}



AppContextServlet 类:
把两个上下文都存入AppContext类中

package com.cal.servlet;


import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cal.utils.AppContext;

public class AppContextServlet extends HttpServlet {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = -9105924604178324202L;

	/**
	 * Constructor of the object.
	 */
	public AppContextServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); 
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init(ServletConfig config) throws ServletException {
		ServletContext servletContext = config.getServletContext();
		AppContext.getInstance().setServletContext(servletContext);
		
		WebApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);  
		AppContext.getInstance().setApplicationContext(appContext); 
	}

}


在容器启动时,把webservice的soap存入 servletContext中

/**
 * WebContainerListener.java
 * 
 * Created Date:	2010-7-12		
 * Last Update:		2010-7-12	    
 * 
 * Copyright (c) Wunderman. All Rights Reserved.
 */
package com.cal.interceptor;

import java.io.File;
import java.io.IOException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.cal.common.Constants;
import com.cal.webservice.SendEmail;
import com.cal.webservice.SendEmailSoap;

/**
 * @version 1.00
 * 
 * <b>修改历史:</b><br>
 * @history 		2010/07/12: 初版 		
 * @author			mahongmin      				
 * @peer review									
 * 
 *
 */
public class WebContainerListener implements ServletContextListener{

	/**
	 * 容器生命周期结束
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		
	}

	/**
	 * 容器初始化
	 */
	public void contextInitialized(ServletContextEvent sce) {
		createLogFile(sce);
		createWSSendMail(sce);
	}
	
	private void createWSSendMail(ServletContextEvent sce){
		SendEmail service = new SendEmail();
		SendEmailSoap soap = service.getSendEmailSoap();
		sce.getServletContext().setAttribute(Constants.WSSOAP, soap);
	}
	
	/**
         *此方法用来在部署项目中创建日志文件
	 * 如果没有日志文件,则创建
	 * @param sce
	 */
	private void createLogFile(ServletContextEvent sce){
		String root = sce.getServletContext().getRealPath("");
		String separator = File.separator ;
		//全部日志
        String logName = "log.log" ;
        //仅错误日志
        String logEName = "error.log" ;
        String directoryLog  = root + separator + "logs";
        String directoryELog  = root + separator  + "logs";
        File fLog = new File(directoryLog , logName) ;
        File fELog = new File(directoryELog , logEName) ;
        if(!fLog.exists()) {
        	fLog.getParentFile().mkdirs() ;
            try {
				fLog.createNewFile() ;
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        if(!fELog.exists()) {
        	fELog.getParentFile().mkdirs() ;
            try {
            	fELog.createNewFile() ;
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        System.setProperty("WORKDIR", root);
	}
}


在web.xml中加入以下代码,使AppContextServlet在容器启动时就启动
 <servlet>
    <servlet-name>AppContextServlet</servlet-name>
    <servlet-class>com.cal.servlet.AppContextServlet</servlet-class>
    <init-param>    
         <param-name>shutdown-on-unload</param-name>    
         <param-value>true</param-value>    
    </init-param>    
    <load-on-startup>1</load-on-startup> 
  </servlet>


在普通类中使用 servletContext和 applicationContext
这样就可以使用hibernate 中的session了
ApplicationContext context = AppContext.getInstance().getApplicationContext();
			SessionFactory sessionFactory = (SessionFactory)context.getBean("sessionFactory");
			DataSource dataSource = (DataSource)context.getBean("dataSource");
			Connection con = dataSource.getConnection();
			Session session = sessionFactory.openSession(con);
			Query query = session.createQuery(" SELECT c FROM Event21 c WHERE c.flag = 1 ");

你可能感兴趣的:(bean,xml,quartz,servlet,webservice)