如何进行Spring自动装配?

时间:2012-11-18 06:08:02

标签: spring autowired

public class ProcessSchedulerServlet implements javax.servlet.Servlet {
    Timer timer=new Timer();

    @Override
    public void init(ServletConfig arg0) throws ServletException {
        timer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            LogProcessorService logProcessorService=new LogProcessorServiceImpl();
            logProcessorService.processPageRequestsLogs();
        }
     }, 60*1000, 120*1000);
}

这很难看,无论如何都不行。 LogProcessorServiceImpl具有带@Autowired注释的属性。运行此代码时,这些属性不会自动装配。这可能是预期的。

真正的问题是:如何使这个run()方法有效。在我看来,Spring希望自动装配logProcessorService以使LogProcessorServiceImpl内的属性自动装配。

===情景1 ========================================== ====================

public void run() {
    final LogProcessorService logProcessorService=null;
    WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getAutowireCapableBeanFactory().autowireBean(logProcessorService);
    logProcessorService.processPageRequestsLogs();
}

结果:编译时错误:不能在不同方法中定义的内部类中引用非最终变量arg0

===情景2 ========================================== ====================

@Autowired
LogProcessorService logProcessorService;
public void run() {
    logProcessorService.processPageRequestsLogs();
}

结果:运行时错误:logProcessorService为null;

====解决方案(来自Boris)====================================== ================

public class ProcessSchedulerServlet implements javax.servlet.Servlet {
    Timer timer=new Timer();

    @Autowired
    LogProcessorService logProcessorService;

    @Override
    public void init(ServletConfig arg0) throws ServletException {
        final AutowireCapableBeanFactory autowireCapableBeanFactory=WebApplicationContextUtils.getWebApplicationContext(arg0.getServletContext()).getAutowireCapableBeanFactory();
        autowireCapableBeanFactory.autowireBean(this);

        timer.scheduleAtFixedRate(new TimerTask() {
            public void run() {
                logProcessorService.processPageRequestsLogs();
            }
        }, 60*1000, 120*1000);
}

1 个答案:

答案 0 :(得分:3)

如果Spring有built in scheduling support,为什么还要使用servlet和Timer类:

@Service
public class LogProcessorService {

    @Scheduled(fixedRate=120*1000, initialDelay=60*1000)
    public void processPageRequestsLogs() {
        //...
    }

}

就是这样!没有计时器,可运行程序和servlet。注意:initialDelay是在Spring 3.2 M1中引入的(参见SPR-7022)。