Announcement Announcement Module
No announcement yet.
Can't use @Autowired in TimerTask Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Can't use @Autowired in TimerTask

    i have a TimerTask class used to run scheduled jobs and when the job runs it executes some transactions on the database so i have a Dao as follows:

        public class CampaignDaoImpl extends BasicDao implements CampaignDao {
            public Campaign getCampaignListById(long id)
                    throws DataAccessLayerException {
                return (Campaign) super.getById(Campaign.class, id);
    and the TimerTask:

        public class CampaignSchedule extends TimerTask {
            private CampaignDao campaignDao;
             public synchronized void schedule() throws DException {
                log.debug("schedule >>> CampaignSchedule");
                Campaign cam= campaignDao.getCampaignListById(1);
    the annotation scanner is set correctly, and the autowiring works fine in other classes in same package
    <context:component-scan base-package="com.mypackage" />
    when debugging i found that campaignDao is null.
    please advise how to fix this error.

  • #2

    I'm afraid you're not giving us enough information in order to effectively help you.

    I just created a very simple project, using just the class names you posted, extending TimerTask, etc, and it's working fine.

    One possible problem is the package name for CampaignDaoImpl. You didn't tell nothing about it. Is it under "com.mypackage".

    What about the log? If you use @Autowired (remember that it's required=true by default), and it can't find a matching bean, then for sure you'll get a org.springframework.beans.factory.BeanCreationExce ption

    By the way, what Spring version are you using?

    Let's do the next. Create a very simple class with this single method:
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/path-to/spring-config.xml");
            CampaignSchedule schedule = context.getBean(CampaignSchedule.class);
    - Put a break into the "System.out.println...".
    - change /path-to/spring-config.xml" as per your configuration.

    Run the class and let us know whether inspecting the "schedule" class, you find the campaignDao to be null.