SpringMvc中,普通類注入Service為null,解決方案
阿新 • • 發佈:2019-02-15
場景:使用Quartz定時器時,普通的java類需要注入spring的service類,在呼叫時報錯!
解決方式:
/**
* 定時獲取課程的service
*/
@Autowired
protected QuartzGetCourseService quartzGetCourseService = (QuartzGetCourseService) SpringContextUtil
.getBean("quartzGetCourseService");
import org.springframework.beans.BeansException; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; /** * 在Spring 註解中,普通類獲取@Service標記的方法或者bean物件 * */ @Component public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } public static ApplicationContext getApplicationContext() { return applicationContext; } /** * 注意 bean name預設 = 類名(首字母小寫) 例如: A8sClusterDao = getBean("a8sClusterDao") * * @param name * @return * @throws BeansException */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } /** * 根據類名獲取到bean * * @param <T> * @param clazz * @return * @throws BeansException */ @SuppressWarnings("unchecked") public static <T> T getBeanByName(Class<T> clazz) throws BeansException { try { char[] cs = clazz.getSimpleName().toCharArray(); cs[0] += 32;// 首字母大寫到小寫 return (T) applicationContext.getBean(String.valueOf(cs)); } catch (Exception e) { e.printStackTrace(); return null; } } public static boolean containsBean(String name) { return applicationContext.containsBean(name); } public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { return applicationContext.isSingleton(name); } }
呼叫結束,測試可以獲取Service.
借鑑文章地址找不到了!