Announcement Announcement Module
Collapse
No announcement yet.
Can't use @Autowired in TimerTask Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • 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:


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

    Code:
    @Service("campaignSchedule")
        public class CampaignSchedule extends TimerTask {
        
            @Autowired
            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
    Code:
    <context:component-scan base-package="com.mypackage" />
    when debugging i found that campaignDao is null.
    please advise how to fix this error.

  • #2
    Hi,

    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:
    Code:
        public static void main(String[] args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/path-to/spring-config.xml");
            CampaignSchedule schedule = context.getBean(CampaignSchedule.class);
            System.out.println("hello");
        }
    - 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.

    Best,
    Carlos.

    Comment

    Working...
    X