Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleApplicationContext
@WebListener
public class NotificationBrokerServletContextListener implements ServletContextListener {
	protected static final String ANNOTATION_CONFIG_CONTEXT = "ANNOTATION_CONFIG_APPLICATION_CONTEXT";

...

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
		applicationContext.register(NotificationBrokerServerSetup.class);
		applicationContext.refresh();
		
		sce.getServletContext().setAttribute(ANNOTATION_CONFIG_CONTEXT, applicationContext);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		Object ctx = sce.getServletContext().getAttribute(ANNOTATION_CONFIG_CONTEXT);
		if(ctx instanceof AnnotationConfigApplicationContext) {
			((AnnotationConfigApplicationContext)ctx).close();
		}
	}


Injection i servlets:servletten

På servlettens init-metode skal AnnotationConfigApplicationContext’en ApplicationContext’en hentes (via ServletContexten) og herigennem skal den aktuelle Servlet have sine afhængigheder injected. Dette skal foregå ved kald til autowireBean og give , hvor Servlet-instansen gives med. Hermed foretages den sidste sammenkædning af ApplicationContext'en, der nu er konfigureret med java-konfigurationsklasserne og Servletten. Med andre ord sørger det for, at afhængigheder injiceres i servletten ved at benytte Spring's autowiring-mekanisme baseret på konfigurationen i ApplicationContext'en.