Подтвердить что ты не робот

Прослушиватель сервлетов

В моем приложении Stripes я определяю следующий класс:

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

  private SomeService someService;

  private AnotherService anotherService;

  // remaining implementation omitted
} 

Сервисный уровень этого приложения использует Spring для определения и соединения некоторой службы beans в файле XML. Я хотел бы ввести beans, которые реализуют SomeService и AnotherService в MyServletListener, возможно ли это?

4b9b3361

Ответ 1

Что-то вроде этого должно работать:

public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
    @Autowired
    private SomeService someService;        
    @Autowired
    private AnotherService anotherService; 

    public void contextInitialized(ServletContextEvent sce) {
        WebApplicationContextUtils
            .getRequiredWebApplicationContext(sce.getServletContext())
            .getAutowireCapableBeanFactory()
            .autowireBean(this);
    }

    ...
}

Ваш слушатель должен быть объявлен после Spring ContextLoaderListener в web.xml.

Ответ 2

Немного короче и проще использовать класс SpringBeanAutowiringSupport.
Чем больше вы должны сделать это:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

Итак, используя пример из axtavt:

public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
    @Autowired
    private SomeService someService;        
    @Autowired
    private AnotherService anotherService; 

    public void contextInitialized(ServletContextEvent sce) {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    ...
}