java定時器無法自動注入的問題解析(原來Spring定時器可以這樣注入service)

來源:互聯網
上載者:User

標籤:context   工具   ram   lua   資料庫   問題   obj   pos   public   

近些日子在做一個項目,在項目中需要用到spring的定時任務,但是在操作資料庫的時候發現總是不能正確的進行資料的插入,經過查看才發現:是因為service層不能夠通過普通的方法注入到action,所以這樣就不能夠執行service層,進而執行資料庫的操作。

解決方案:這時需要配置一個service注入的工具類,代碼如下:

一、工具類

public class ApplicationContextUtil implements ApplicationContextAware {          private static ApplicationContext applicationContext;          public static ApplicationContext getApplicationContext() {              return applicationContext;          }          public void setApplicationContext(ApplicationContext applicationContext) {              ApplicationContextUtil.applicationContext = applicationContext;          }          public static Object getBean(String beanName) {              return applicationContext.getBean(beanName);          }      }
二、配置bean
<bean  id ="applicationContextUtil"  class ="org.sihai.soil.util.ApplicationContextUtil" ></bean >
三、定時器中通過ApplicationContextUtil類,獲得service。
realmEbi = (RealmEbi) ApplicationContextUtil.getBean("realmEbi");        realmEbi.insertHour(RealmApplianceModel.sendData3);

完美解決了,這樣我們就可以擷取到service對象進行相對應的業務處理,而不需要再建立jdbc來操作了。

java學習群669823128

java定時器無法自動注入的問題解析(原來Spring定時器可以這樣注入service)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.