自动化应用程序上下文

我试图在我的Spring MVC项目ImageCreatorUtil WebApplicationContext自动assembly到我创建的类ImageCreatorUtil中。 在使用应用程序上下文的类中执行方法时,我总是收到一个NPE。 请务必注意,此方法由另一个配置文件中定义的ApplicationListener调用。 我不确定为什么自动assembly不起作用。 有人可以提供任何建议吗?

servlet的context.xml中

                                 

ImageCreatorUtil.java

 @Component public class ImageCreatorUtil { static Logger logger = LoggerFactory.getLogger(ImageCreatorUtil.class); static final String IMAGE_PATH_FRAGMENT = "/resources/images/resume/skills/uploaded-icons/"; @Autowired private WebApplicationContext context; /** * Creates the provided file in the resources directory for access by the * web application. * * @param appContext * @param image */ public void storeImage(Image image) { if (image != null) { String realPath = ((WebApplicationContext)context).getServletContext().getRealPath("/"); File tmpFile = new File(realPath + IMAGE_PATH_FRAGMENT + image.getName()); try { logger.info("Saving image to :" + tmpFile.getAbsolutePath()); FileUtils.writeByteArrayToFile(tmpFile, image.getFile()); } catch (IOException e) { e.printStackTrace(); } } } } 

应用程序的context.xml

                       

控制台错误

 SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener java.lang.NullPointerException at org.tothought.spring.utilities.ImageCreatorUtil.storeImage(ImageCreatorUtil.java:34) at org.tothought.spring.listeners.ImageLoaderApplicationListener.onApplicationEvent(ImageLoaderApplicationListener.java:29) at org.tothought.spring.listeners.ImageLoaderApplicationListener.onApplicationEvent(ImageLoaderApplicationListener.java:1) at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:97) at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:324) 

我试过你的代码。 上下文自动assembly在任何控制器类中对上下文进行罚款,但是当我使用类的对象调用方法时它不起作用。 所以如果你做的事情如下:

你的控制器:

 @Autowired private ImageCreatorUtil icu; public String controllerMethod(....) { icu.storeImage(); } 

你的application-context.xml:

  

然后自动assembly将正常工作。 我会尝试更新你这种行为的原因。