Timed tasks in Spring task fail to inject service solution

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.