我的豆是:
@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!
答案 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 );
}
}