解決SpringMvc中普通類註入Service為null的問題

SpringMvc中普通類註入Service為null

場景:

使用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.

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
    }      
}  

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: