因爲spring 建立的bean默認都是單例的,在線程中不容許直接注入的,因此咱們經過Spring的上下文去獲取dao。java
首先 實現這個接口ApplicationContextAware web
package com.eimageglobal.edu.web.watchDog; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringApplicationContextHolder implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext context) throws BeansException { SpringApplicationContextHolder.context = context; } public static Object getSpringBean(String beanName) { return context==null?null:context.getBean(beanName); } public static String[] getBeanDefinitionNames() { return context.getBeanDefinitionNames(); } }寫完後須要在spring 中用bean 注入配置一下spring
<bean class="com.XXXXXX.SpringApplicationContextHolder" />
在線程業務中 就要經過getSpringBean(「名字」)獲取須要的對象,dom
EduogDao eduDao = (EduogDao ) SpringApplicationContextHolder
.getSpringBean("eduCXXXgDao");ide這裏的 「名字」 是要和你在 spring 中配置的要一致,配置以下(和上面的配置是兩個配置):this
<bean id="eduCouXXXXXogDao" class="com.XXXXXXXXX.EduCourXXXXXXXogDaoImpl"></bean>
注意這兩個spring 中的配置都是須要的線程
下面說是在線程業務中調用了code
package com.eimageglobal.edu.web.watchDog; import java.util.Iterator; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import com.eimageglobal.edu.biz.dao.EduCourseCollectLogDao; import com.eimageglobal.edu.biz.domain.model.EduAttendMunber; import com.eimageglobal.edu.biz.domain.model.EduCourseCollectLogModel; public class ConferenceTh implements Runnable { private static ConcurrentHashMap<String, EduWatch> educList = new ConcurrentHashMap<String, EduWatch>(); boolean flag = true; public ConcurrentHashMap<String, EduWatch> getEducList() { return this.educList; } public void run() { if (flag) { while (true) { try { synchronized (EduWatch.class) /* 使用了靜態,鎖就變了 */ { System.out.println("---------------------心跳監聽"); if (!educList.isEmpty()) { for (String key : educList.keySet()) { EduWatch ew = educList.get(key); List<EduAttendMunber> attmList = ew.getNumberlist(); try { Iterator<EduAttendMunber> it = attmList.iterator(); while (it.hasNext()) { EduogDao eduDao = (EduogDao ) SpringApplicationContextHolder .getSpringBean("eduCXXXgDao"); //這個地方的名稱就是前面在spring 中配置的須要在線程中注入的dao ecm.setId(eduAttendMunber.getId()); ecm.setUserId(eduAttendMunber.getDoctorId()); eduCourXXXXgDao.endLearnLog(ecm); it.remove(); } }catch (Exception e){ e.printStackTrace(); } educList.remove(key); } } } } catch (Exception e) { e.printStackTrace(); } } } } }
在線程業務中獲取dao 的代碼就這一句xml
EduogDao eduDao = (EduogDao ) SpringApplicationContextHolder
.getSpringBean("eduCXXXgDao");對象這樣就能在線程中使用spring 中dao 了。