1. Questions
Because a project (using the Spring+springmvc+hibernate framework) requires a database operation to be called in the Spring Task Timer task, the background error occurs when the service is injected with the @Autowired, causing the system to be inaccessible.
2. Code
The code for the timed task is as follows:
@Component
public class Taskjob {
Logger Logger = Logger.getlogger (Taskjob.class);
@Autowired
Private Tempservice Tempservice;
@Scheduled (cron = "* */1 * *?")
public void Getdoortoken () {
Timed execution of code requires
... Database operations ...
}
3. Cause analysis
Because the execution priority of the timing @Scheduled is higher than @autowired injection, we cannot inject the service through @autowired.
4. Solutions
Perform subsequent database operations by locating instances of the service by name in ApplicationContext in a timed task.
4.1 Example code in a timed task: tempservice tempservice = (tempservice) applicationcontextutil.getbean ("Tempservice");
4.2 Find the Service code example in ApplicationContext:
The key is to implement Applicationcontextaware and to inject in spring
@Component
public class Applicationcontextutil implements Applicationcontextaware {
private static ApplicationContext context;
@Override
public void Setapplicationcontext (ApplicationContext applicationcontext) throws Beansexception {
context = ApplicationContext;
}
public static ApplicationContext Getapplicationcontext () {
return context;
}
public static Object Getbean (String name) {
Return Getapplicationcontext (). Getbean (name);
}
...... Other code ...
}
Timed tasks in Spring task fail to inject service solution