Spring在服务器启动期间将bean注入启动类

时间:2012-07-03 02:39:29

标签: spring timertask

我的豆是:

@Component
public class KidsServerStartUp implements ServletContextListener
{
     UploadService uplService;

    @Autowired
    public void setUplService( UploadService uplService )
    {
        this.uplService = uplService;
    }
    public void contextInitialized(ServletContextEvent event) {
       System.out.println ( uplService );
    }
}

在web.xml中;我首先调用spring框架来设置所有bean;然后设置启动监听器:

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <listener>
        <listener-class>com.kids.util.KidsServerStartUp</listener-class>
    </listener>

uplService被打印为null!

1 个答案:

答案 0 :(得分:3)

我认为你要找的是this post

由于您使用的是ServletContextListener弹簧上下文,因此不会用于创建Listener类。但我们可以使用ApplicationContext访问ServletContext

public class KidsServerStartUp implements ServletContextListener {
    public void contextInitialized(ServletContextEvent event) {
        final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
        UploadService uplService = springContext.getBean(UploadService.class);
        System.out.println ( uplService );
    }
}