Results 1 to 2 of 2

Thread: injecting bean into ServletContextListener

  1. #1
    Join Date
    Oct 2006
    Posts
    1

    Default injecting bean into ServletContextListener

    I am not sure there is another solution to this, but I thought I would throw it out there.
    I am attempting to inject a service level bean into a listener. The listener is defined in the web.xml and wired in a Spring config file. Obviously, I can't define parameters in web.xml, but I have set the params in Spring.
    On startup, the webapp instantiates the listener (and obviously does not set the bean). Then, Spring instantiates the listener and sets the bean, as expected. When contextInitialized is called, it is naturally called on the webapps instance of the listener (with no bean reference).
    This behavior is obviously expected, and I have come up with 2 workarounds. One is to simply make the bean member a static (which works because contextInitialized() is called after Spring sets the bean). The second is to use the WebApplicationContext to find the bean by id. Both of these work, but they are not very elegant.
    Does anyone know of a better way to do this?

    Thanks.

  2. #2
    Join Date
    Jan 2005
    Location
    Bucharest, Romania
    Posts
    5,403

    Default

    I don't think there is an easy way out of this since the ContextListener is maintained by the web container (instantiated and configured). Dependency lookup (as opposed to dependency injection) is the only way to go by using the WebAppCtx, something which you already do.
    one idea would be to use a delegation listener which will lookup a listener configure in Spring and delegate all methods to that instance.
    However, you'll have to make sure that the lifecycles of the listeners match .
    Costin Leau
    SpringSource - http://www.SpringSource.com- Spring Training, Consulting, and Support - "From the Source"
    http://twitter.com/costinl
    Please use [ c o d e ] [ / c o d e ] tags

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •