本篇内容介绍了“如何解决SpringMvc中普通类注入Service为null的问题”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
SpringMvc中普通类注入Service为null
场景:
使用Quartz定时器时,普通的java类需要注入spring的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; @Componentpublic 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; } public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } @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.
spring之工具类使用service注入
一般需要在一个工具类中使用@Autowired 注解注入一个service。但是由于工具类方法一般都写成static,所以直接注入就存在问题。
栗子:
@Component public class SmsController { private static Logger logger = LoggerFactory.getLogger(SmsController.class); @Autowired private MessagesInfoService messagesInfoService; private static SmsController smsController; @PostConstruct public void init() { smsController = this; smsController.messagesInfoService = this.messagesInfoService; } @RequestMapping(value = "/queryMessage",method = RequestMethod.GET) public ModelAndView queryMessage{ pager = messagesInfoService.findPager(map,5,pIndex); ModelAndView modelAndView = new ModelAndView("manage/jgdxgl/jgdx_qm"); List<MessagesInfo> list = pager.getItem(); modelAndView.addObject("pager",pager); modelAndView.addObject("list",list); return modelAndView } }
“如何解决SpringMvc中普通类注入Service为null的问题”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注编程网网站,小编将为大家输出更多高质量的实用文章!