Page History
...
| Info |
|---|
DI.1.7 § ApplicationContext'en skal oprettes og nedlægges ved hhv. contextInitialized og contextDestroyed på ServletContext'en. |
Her demonstrert ved NotificationBrokerens implementation:
| Code Block | ||||
|---|---|---|---|---|
| ||||
@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:
På servlettens init-metode skal AnnotationConfigApplicationContext’en hentes (via ServletContexten) og herigennem skal den aktuelle Servlet have sine afhængigheder injected. Dette skal foregå ved kald til autowireBean og give Servlet-instansen med.
...