views:

150

answers:

1

I am new to spring and I am currently using ClassPathXmlApplicationContext to getBean inside the controller class. This is a small example application I am building. But what I am trying to do is to move this ClassPathXmlApplicationContext to a new class and keep it static across application. So I can just call the newclass to invoke the DAO inside constructor. I tried a few things but I am getting NestedServletException error all the time.

Please suggest me a way to write my new class for data connection which will remain in the same state across my application, i.e. I can just call inside each controller class and not create a DAO object in constructor each time.

Appreciate any help, suggestion.

thanks Walker

+2  A: 

As I assume from the exception name, you are talking about a web application. In that case there is no need for you to create the application context. Spring has its built-in mechanisms. For example, use a listener (in web.xml)

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

And so all your beans are getting automatically wired by spring (if, of course, configured properly).

You can still get ahold of the context either via implementing ApplicationContextAware or by callign WebApplicationContextUtils.getRequiredWebApplicationContext(), but you shouldn't need this in the general scenario.

You should not use the application context manually. Instead, spring wires your application using dependency injection and all your objects (controllers, daos, etc) have their dependencies in place, without the need to "reach" for them in some context.

Bozho
Thanks Bozho for the quick reply. I think this will solve my problem. I will give it a shot. Thanks :)
Walker