0

我的豆是:

@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 !

4

1 回答 1

3

我认为您正在寻找的是类似这篇文章的内容。

由于您使用的是ServletContextListenerspring 上下文,因此不会用于创建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 );
    }
}
于 2012-07-03T04:19:49.203 回答