Matin Kh
Matin Kh

Reputation: 5178

Can't a Filter or Listener use spring beans?

I have a listener class in web.xml like this:

<listener>
    <listener-class>com.datx.monitoring.model.MonitoringHttpSessionListener</listener-class>
</listener>

And for this class, I have defined a bean like this:

<bean id="monitoringHttpSessionListener"
    class="com.datx.monitoring.model.MonitoringHttpSessionListener" autowire="byName"/>

But this bean is not able to use other beans. Every time this class is called, it has null properties.

This class is the exact same as the other which is working fine. The only difference is, this class is used as a listener and the other is not. Why is that?

Upvotes: 0

Views: 322

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328674

There is a simple reason for this: There are two beans. One was created by your web container (which uses web.xml) and the other by Spring (which uses your bean definition). The web container and Spring know nothing about each other.

What you need to do is create a normal listener which gets the application context with

WebApplicationContextUtils.getWebApplicationContext(session.getServletContext());

This will allow you to look up beans. Now you can define a bean which the filter can modify.

Note: You will want to give this bean the request scope or there will be chaos.

Upvotes: 1

Related Questions