Analysis of the problem that java timers cannot be injected automatically (the original Spring timers can be injected into services in this way)

 

Reprint https://www.cnblogs.com/rese-t/p/8321773.html

I have been working on a project in recent days, and I need to use spring's timed tasks in the project, but when I operate the database, I find that the data cannot be inserted correctly. The method is injected into the action, so it is impossible to execute the service layer and then perform database operations.

Solution: At this time, you need to configure a tool class for service injection. The code is as follows:

1. Tools

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

Second, configure the bean

<bean  id ="applicationContextUtil"  class ="org.sihai.soil.util.ApplicationContextUtil" ></bean >

3. The service is obtained through the ApplicationContextUtil class in the timer.

realmEbi = (RealmEbi) ApplicationContextUtil.getBean( "realmEbi");
        realmEbi.insertHour(RealmApplianceModel.sendData3);

Perfectly solved, so that we can get the service object for the corresponding business processing, without the need to create jdbc to operate.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326247655&siteId=291194637